在`.add`中运行一个函数

时间:2017-04-25 17:39:38

标签: javascript

好的,我正在使用Observable.add添加照片,但我需要运行一个函数/请求来获取UserNameFeed信息,问题是我可以从在.add

var Photo = Observable();
Photo.add({
    photoDateFeed: element.theDate, 
    imgurl: "https://res.cloudinary.com/" + element.photos.value,
    UserFEEDid: element.userid,
    UserNameFeed: ( run a javascript function??? )
});

我不确定这是否可能

1 个答案:

答案 0 :(得分:2)

您可以在下一步中执行此操作:

  1. 实施功能。
  2. 来电。
  3. 最终代码将如此

    function yourFunction(){
       var result = 'Name';// Do what you want
       return result;
    }
    var Photo = Observable();
    Photo.add({
        photoDateFeed: element.theDate, 
        imgurl: "https://res.cloudinary.com/" + element.photos.value,
        UserFEEDid: element.userid,
        UserNameFeed: yourFunction()
    });
    

    如果你的函数需要接受参数,只需在参数列表中加入

    function yourFunction(element){
       var result = 'Name ' + element.userid;// Do what you want
       return result;
    }
    var Photo = Observable();
    Photo.add({
        photoDateFeed: element.theDate, 
        imgurl: "https://res.cloudinary.com/" + element.photos.value,
        UserFEEDid: element.userid,
        UserNameFeed: yourFunction(element)
    });
    

    如果您需要进行异步操作,则必须将其重写为异步样式:

    function yourFunction(element, callback){
       // get name in async
       $.ajax({
           ...
           success: function(result) {
               // Do what you want
               callback(result)
           }
       });   
    }
    var Photo = Observable();
    yourFunction(element, function(result){
       Photo.add({
           photoDateFeed: element.theDate, 
           imgurl: "https://res.cloudinary.com/" + element.photos.value,
           UserFEEDid: element.userid,
           UserNameFeed: result
       });
    });