拜托,有人能帮我吗?
在执行create方法时,我得到了以下错误:
*Uncaught TypeError: Object #<Object> has no method 'baseUri'*通过以下绑定调用此方法:
<form id="createProducts" data-bind="submit: products.create">当执行read方法(从PreLoad方法调用)时,baseUri和items都可用。
当视图模型被定义为一个函数时,我找到了解决这个问题的方法,但在我的例子中,它被定义为一个对象。
这是我的完整JS文件
var mm = {
/* Products ********************************************************** */
products: {
items: ko.observableArray([]),
read: function () {
$.getJSON(this.baseUri(), this.items);
},
create: function (formElement) {
$.post(this.baseUri(), $(formElement).serialize(), null, "json")
.done(function (o) {
alert("The Product " + o.Name + " was created.");
this.items.push(o);
});
},
baseUri: function () { return BASE_URI; }
}
};
function PreLoad() {
mm.products.read();
ko.applyBindings(mm);
}谢谢!
发布于 2012-11-19 21:22:53
在绑定事件时,有两种方法可以确保this是正确的。
第一个是使用bind
<form id="createProducts" data-bind="submit: products.create.bind(products)">第二种方法是使用内联函数:
<form id="createProducts" data-bind="submit: function() { products.create(); }">这种行为将来可能会改变(请参阅https://github.com/SteveSanderson/knockout/issues/378)。
编辑
有两种解决方案可以使this在回调函数中可用。第一种方法是将this复制到通过闭包可用的局部变量。
var self = this;
$.post(this.baseUri(), $(formElement).serialize(), null, "json")
.done(function (o) {
alert("The Product " + o.Name + " was created.");
self.items.push(o);
});第二种方法是对回调函数使用bind。
$.post(this.baseUri(), $(formElement).serialize(), null, "json")
.done(function (o) {
alert("The Product " + o.Name + " was created.");
this.items.push(o);
}.bind(this));发布于 2012-11-19 01:57:28
我有一种感觉,当你打电话给this时,products.create不是你想的那样。尝试使用.bind显式设置上下文:
<form id="createProducts" data-bind="submit: products.create.bind($data)">发布于 2012-11-19 08:54:18
正如安德鲁·惠特克( Andrew )已经提到的那样--“这”将不是你所期待的背景。我的解决方案是存储"this“引用(如称为"self"),并使用它而不是"this":
products: {
self: undefined,
items: ...,
init: function() {
this.self = this;
},
read: function () {$.getJSON(self.baseUri(), self.items);},
create: function () {
$.post(self.baseUri(), $(formElement).serialize(), null, "json")
.done(function (o) {
alert("The Product " + o.Name + " was created.");
self.items.push(o);
});
},
baseUri: function () { return BASE_URI; }
};
function PreLoad() {
mm.products.init();
mm.products.read();
ko.applyBindings(mm);
}您还可以显式地指示应该在哪个上下文函数中调用:
<form id="createProducts" data-bind="submit: function () { products.create($root.products); }">
products: {
create: function(self) {
...
}在这种情况下,$root应该指向您的视图模型,因此您将传递products对象的实例来创建函数。
https://stackoverflow.com/questions/13444045
复制相似问题