What's this "ko.observable" stuff?

Discussion in 'Mod Discussions' started by killerkiwijuice, March 1, 2015.

  1. killerkiwijuice

    killerkiwijuice Post Master General

    Messages:
    3,879
    Likes Received:
    3,597
    I see these things everywhere, they look pretty important.

    I think ko. stands for Knockout, I just have no idea what these things are actually doing.

    I've gotten better with the other stuff (rest of JS), I can figure out how the more complicated mods are made just by looking at the source now.

    So yeah, can someone please enlighten me on the ko.<insertwordhere> stuff? :p
  2. mikeyh

    mikeyh Post Master General

    Messages:
    1,869
    Likes Received:
    1,509
  3. killerkiwijuice

    killerkiwijuice Post Master General

    Messages:
    3,879
    Likes Received:
    3,597
    Is knockout something that PA uses for it's development or is it just something native in JS?
  4. mikeyh

    mikeyh Post Master General

    Messages:
    1,869
    Likes Received:
    1,509
    It's one of many third party JavaScript frameworks like bootstrap, jQuery/UI, lodash, strophe (xmpp) etc.

    Take a look at ui/main/shared/js/thirdparty
  5. Raevn

    Raevn Moderator Alumni

    Messages:
    4,226
    Likes Received:
    4,324
    Making a variable into a knockout observable allows you to use it in a way that will automatically update when the variable changes.

    Most of the UI uses observables, as it ensures the UI remains up-to-date without having to write a lot of auxiliary code.

    The javascript side of things is easy. You declare an observable like this:
    Code:
    var testObservable = ko.observable();
    You can also set a default value like this:
    Code:
    var testObservable = ko.observable(<default value>);
    This actually makes testObservable into a function. To change the value for an observable, you then call the function with the new value as a parameter:
    Code:
    testObservable(<new value>);
    To get the current value, call the function without a parameter:
    Code:
    testObservable();

    On the UI/html side of things, there are several ways you can use this variable:

    Set the text of a div/element to the observable value:
    Code:
    <div data-bind="text: testObservable()"></div>
    Give a div/element a css class based on the observable value (boolean):
    Code:
    <div data-bind="css: {'new-css-class': testObservable()}"></div>
    You can selectively show areas of HTML based on observable values:
    Code:
    <!-- ko if: testObservable() == true -->
        <div>HTML code here</div>
    <!-- /ko -->
    All of the above HTML parts will automatically update whenever the underlying observable is modified. There are also many other bindings you can do; have a look at the KO documentation here.

    In addition to straight observables, there are also ko.observableArray and ko.computed.

Share This Page