Backbone.View无法调用函数

时间:2011-08-06 18:10:07

标签: javascript jquery backbone.js underscore.js

我正在尝试调用函数,但是我收到一个错误,声明函数未定义。

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()')

1 个答案:

答案 0 :(得分:0)

作为一个简单的解决方案,您应该可以:

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资源的集合中使用每个方法时才可用,因此在这种情况下不适用。例如,如果您有一组消息,则可以执行以下操作以保留上下文。

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