繁体   English   中英

Backbone.View无法调用函数

[英]Backbone.View cannot call a function

我正在尝试调用一个函数,但出现错误,说明函数未定义。

window.PackageView = Backbone.View.extend({

    tagName: "div",

    className: "package-template",

    events:{

      "click #display-name"       :    "getNodeId",         
    },

    initialize: function() { 
        _.bindAll(this,'render', 'getNodeId', 'getAction');                      
        this.template = _.template($('#package-template').html());
        $(this.el).html(this.template); //Load the compiled HTML into the Backbone "el"
        nodeInstance.bind('reset', this.render, this);
    },

    render: function() {
       //.. no need to worry about this.
    },


    getNodeId: function(){
        objectJSON = jAccess.getJSON(); // I get the JSON successfully
        nodeIdArray = []
        _.each(objectJSON, function(action){
            _.each(action.Nodes, function(action){
                nodeIdArray.push(action.Id);
                  this.getAction(); // Here is the problem. I get an error
            });    
        });    
    },

    getAction: function(){

       actionsArray = [];
       objectJSON = jAccess.getJSON();
       _.each(objectJSON, function(action){
           _.each(action.Nodes, function(action){
               if(action.Id == 5) {       

               _.each(action.Actions, function(action){
                   actionsArray.push(action.Name);
               });
            }
           });
       });
       console.log(actionsArray);
    }


});

我不知道我要去哪里错了。 帮帮我。

我收到一条错误消息,指出“未定义”不是函数求值('this.getAction()')

作为一个简单的解决方法,您应该能够:

getNodeId: function(){
    var self = this;
    objectJSON = jAccess.getJSON();
    nodeIdArray = []
    _.each(objectJSON, function(action){
        _.each(action.Nodes, function(action){
            nodeIdArray.push(action.Id);
              self.getAction();
        });    
    });    
},

我认为使用下划线绑定功能可能会有更优雅的解决方案,我将进行检查。

编辑仅当在RESTful资源的集合上使用each方法时,才可以使用更优雅的解决方案,因此在这种情况下不适用。 例如,如果您有一组消息,则可以执行以下操作来保留上下文。

  addAllMessages: function(messages) {
        messages.each(this.addMessage, this);
    },

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM