Javascript 主干。视图无法调用函数
我试图调用一个函数,但出现一个错误,说明函数未定义Javascript 主干。视图无法调用函数,javascript,jquery,backbone.js,underscore.js,Javascript,Jquery,Backbone.js,Underscore.js,我试图调用一个函数,但出现一个错误,说明函数未定义 window.PackageView = Backbone.View.extend({ tagName: "div", className: "package-template", events:{ "click #display-name" : "getNodeId", }, initialize: 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);
}
});
我不知道我哪里出了问题。帮帮我
我收到一个错误,说“undefined”不是一个函数求值('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);
},
这可能是一个范围问题。根对象console.log(this)在getNodeId()开头和this.getAction()前面的行中的值是多少?如果它们不匹配,那么这肯定是一个范围问题。我不知道。我必须检查一下。它在
this.getAction()
之前和objectJSON=jAccess.getJSON()之前显示DOMWindow@Eric:你真的需要阅读主干文档-在编码时一直打开它:)-它在这里解决了这个问题:。