简体   繁体   中英

Why is .bind() used in this example?

var TwitterListModel = function (lists, selectedList) {
    // [...]

    this.addUser = function () {
        if (this.userNameToAdd() && this.userNameToAddIsValid()) {
            this.editingList.userNames.push(this.userNameToAdd());
            this.userNameToAdd("");
        }
    };

    this.removeUser = function (userName) {
        this.editingList.userNames.remove(userName)
    }.bind(this);

    // [...]
}

I've found this code in this page from Knockout JS examples. They are declared inside of an object. I'd like to understand why the first function doesn't use .bind(this) and the second does.

When and why is it necessary to use .bind(this) ? It looks like if I use it or not makes no difference: the meaning of this is always referred to the object in which the method is declared (and not the anonymous function in which it is found). Am I right?

Both these methods access this.editingList and they're referring to the same variable in both cases.

You can play with the fiddle they provide for this example...

If you try to remove the .bind(this) you will see that this (add a console.log(this) in this method) then refers to the username. This is due to the fact that the removeUser function is bind on the button in the loop over the usernames ( <ul data-bind='foreach: userNames'> ).

For the other binding, it is attached to the form and then goes with the whole model.

好像removeUser意在回调中使用,并在回调this将不是指TwitterListModel,所以他们明确指定TwitterListModel因为this给函数

removeUser is bound to the context of the row in the array.

$root points out the parent, but when the click handler is called the this context will be pointing to the item clicked. This is by design by the KO team.

You can also solve it like this

<button data-bind='click: $root.removeUser.bind($parent)'>Remove</button>

This will also work with protoype function declaration

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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