Search code examples
observablejsviews

Observable helpers in JS Views


I'm trying to have an element update based on an observable fed to a helper.

Observable:

var siteGlobal = {
    page: null,
    parent: null
};

Helper

$.views.helpers({
    navState: function(id) {
        var cssClass = "nav_item";
        if (Number(id) === siteGlobal.parent) {
            cssClass += " current_page_parent";
        } else if (Number(id) === siteGlobal.page) {
            cssClass += " current_page_item";
        }
        return cssClass;
    }
});

$.views.helpers.navState.depends = [siteGlobal, "parent"];
$.views.helpers.navState.depends = [siteGlobal, "page"];

Element

<li data-link="class{:~navState(id)}" >...</li>

So the idea is that when the observable changes, the helper responds, comparing the value supplied from the linked element.


Solution

  • Yes, that will work.

    You need

    $.views.helpers.navState.depends = [siteGlobal, "parent", "page"];
    

    Now if id is 3, and you call

    $.observable(siteGlobal).setProperty("page", 3);
    

    then class will get set to "nav_item current_page_item"

    Call

    $.observable(siteGlobal).setProperty("parent", 3);
    

    and it will get set to "nav_item current_page_parent"

    See www.jsviews.com/#computed@depends.