Javascript原型和访问“this”的父对象
Javascript prototype and accessing parent object of 'this'
在杜兰达尔,我正在开发一个列出许多医生的页面。每行都有一个删除按钮。这是我的视图模型:
var Doctor = function() {};
Doctor.Model = function(data) {
this.id = data.id;
this.name = ko.observable(data.name);
};
Doctor.prototype.activate = function() {
this.doctorArr = ko.observableArray();
// Start Doctor List
this.load();
};
Doctor.prototype.load = function() {
// load list into this.doctorArr()
}
Doctor.prototype.remove = function() {
console.log(this);
};
这是我的观点:
<button data-bind="click: remove">Remove Function</button>
<ul data-bind="foreach: { data: doctorArr }">
<li>
<span data-bind="text: name"></span> - <a data-bind="click: $parent.remove">Delete...</a>
</li>
</ul>
单击<button>
将返回:
Doctor {doctorArr: function, activate: function…}
但是单击 foreach 函数内的链接将返回模型:
Doctor.Model {id: "104", name: function}
问题是当"this"返回模型时,我无法弄清楚如何从删除函数内部访问 doctorArr。我需要它来删除该项目。
您需要使用方法bind
来更改您正在调用的函数中这个(范围(的"含义"。您有一些选择:
添加bind
以在所需范围内调用视图模型:
<li>
<span data-bind="text: name"></span> - <a data-bind="click: $parent.remove.bind($parent)">Delete...</a>
</li>
如果要在视图模型中不使用方法将其删除。这将神奇地从数组中删除该项目:
<li>
<span data-bind="text: name"></span> - <a data-bind="click: $parent.doctorArr.remove.bind($parent.doctorArr)">Delete...</a>
</li>
问题是在你的视图模型中,你没有分配"this"是什么,所以每次你调用 remove 时,它都会在不同的上下文中传递。
var Doctor = function() {};
Doctor.Model = function(data) {
var self = this;
this.id = data.id;
this.name = ko.observable(data.name);
};
Doctor.prototype.activate = function() {
var self = this;
this.doctorArr = ko.observableArray();
// Start Doctor List
this.load();
};
Doctor.prototype.load = function() {
var self = this;
// load list into this.doctorArr()
}
Doctor.prototype.remove = function() {
var self = this;
console.log(this);
};
传递给
事件绑定的第一个参数 KNOCKOUT 是根模型:
Doctor.prototype.remove = function(model) {
console.log(model.doctorArr);
};
相关文章:
- javascript中对象构造函数中的var属性与this.properties
- 定义this.properties或objectName.properties的javascript JSON对象
- 如何使用(this)访问Angular 2 http rxjs catch函数中的对象属性
- Javascript 对象和 this 关键字
- jquery$(this)对象缺少问题
- Javascript对象来获取父方法的this
- 如何绑定“;这个“;在$http.post中->在AngularJS中解析/拒绝?(现在this=Window对象
- 将“this”关键字发送到对象中
- jQuery双对象构造函数-例如$($(this))
- ui.selectmenu投掷'this.newelement.0'为null或不是对象
- 警告 - 全局 THIS 对象的危险使用
- $.each 中的“this”,当需要使用“this”访问对象的函数时
- Javascript对象文字,如何使用“this”来引用对象中的变量
- 为什么当我尝试将函数绑定到自身时,“this”对象仍然引用窗口
- TypeScript:在对象文字字段中的访问器中访问外部“this”
- 在将对象传递给数组时,在 this.x 上给“x”一个变量值
- 将对象this发送到不带参数的函数
- 使用HTML5音频和jQuery对调用对象(this)的引用
- Javascript在对象中使用绑定,我如何访问对象this
- 无法使用“this”访问对象.“this”指向“窗口”对象