简体   繁体   中英

Knockout.js event context

I started reimplementing some js code with knockout.js. I have a singleton with some functions in it:

Dps = {
    someFunction: function() {
        this.anotherFunction();
    },
    anotherFunction: function() {
        console.log('tehee');
    }
}

Now there are also some bindings which calls functions of this singleton:

<input type="text" data-bind="event: { change: Dps.someFunction }" />

The annoying thing is, that the context in the called function is the event, so I can't call this.anotherFunction()

Is there a nice way to get rid of this?

PS: I'm aware that I could do something like Dps.someFunction() instead, but this is not nice in my opinion.

data-bind="event: { change: Dps.someFunction.bind(Dps) }"

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind

Your functions behaves as "static"

So either you have to do Dps.anotherFunction but you don't want that, but I don't see why tbh.

You can also call ko.applyBindings(Dps) and then your code would work fine. However I guess that's not what you're looking for either. Probably you have another viewmodel all together, no?

Another solution is to make Dps into a function which you instantiate

On jsfiddle: http://jsfiddle.net/PrbqZ/

<input type="text" data-bind="event: { change: myDps.someFunction }" />

var Dps = function() {
    var self = this;
    this.someFunction = function() {
        self.anotherFunction();
    };

    this.anotherFunction = function() {
        console.log('tehee');
    };
}

var myDps = new Dps();

//normally use dom ready, just simulating here
setTimeout(function(){
    ko.applyBindings();
}, 500)

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