user736893
user736893

Reputation:

calling viewmodel functions from element bound using applyBindingsToNode fails

I just started playing with applyBindingsToNode, which is working great for what I wanted with one caveat... functions don't seem to work.

    ko.applyBindingsToNode(newNode.get()[0], {
        //template: { name: 'relationshipNode', data: ent },
        click: ent.select, //does not work
        clickBubble: false,
        event: {
            contextmenu: ent.rightClick, //does not work
            mouseover: ent.toggleHover, //does not work
            mouseout: ent.toggleHover //does not work
        },
        attr: {
            'data-name': ent.name, //works
            'data-type': ent.type //works
        },
        css: {
            selected: ent.selected, //works
            hover: ent.hovered //works
        },
        text: ent.name //works
    })

Here's an example, the hover function

    self.toggleHover = function (entity, event) {
        entity.hovered(!entity.hovered());
    }

It throws an error because "entity" is undefined.

All these functions work fine on an element created at runtime with the data-bind attribute, like so:

<div data-bind="click: select, clickBubble: false, event: { contextmenu: rightClick, mouseover: toggleHover, mouseout: toggleHover }, attr: {'data-name': name, 'data-type': type }, css: { selected: selected, hover: hovered }"></div>

Upvotes: 2

Views: 498

Answers (1)

RP Niemeyer
RP Niemeyer

Reputation: 114792

ko.applyBindingsToNode (and ko.applyBindingAccessorsToNode added in 3.0) take in 3rd argument that is the binding context. This context is used by many of the bindings (event/click, template, control-flow bindings).

Upvotes: 2

Related Questions