Search code examples
javascriptmodel-view-controllerderbyjs

Derby.js - adding/removing unique list elements


I have this as my bootstrapped data, which I push to the model when nothing is retrieved from the DB:

var liveaudience = {

triggers : [
    {
        'trigger_id': 'vocal_stomp',
        'duration': 1000,
        'color': '#F23000',
        'sound': 'A#'
    },
    {
        'trigger_id': 'guitar_stomp',
        'duration': 600,
        'color': '#CC0234',
        'sound': 'Cmaj'
    },
    {
        'trigger_id': 'drum_pad',
        'duration': 1200,
        'color': '#CF2451',
        'sound': 'Emin'
    }
]

};

I have this one route, which does this and then renders these three bootstrapped elements on the template:

get('/:triggerId?', function(page, model, params){

    var triggers = model.get('liveaudience.triggers');
    if(typeof triggers === 'undefined'){
         // bootstrap triggers
         model.push('liveaudience.triggers', liveaudience.triggers);
    }

    model.subscribe("liveaudience.triggers", function(err, scopedModels){
        page.render({'triggers': scopedModels.get()[0]});
    });
});

and then here is the template:

<ul id="triggers">
        {{#each triggers}}
            <li data-id="{{id}}" class="trigger" style="background-color:{{color}};">
                <span class="trigger-label">{{trigger_id}}</span>
                <a x-bind="click:removeTrigger" class="remove-trigger">x</a>
            </li>
        {{/}}
    </ul>

Everything shows up, but {{id}} returns a function, and I'd like it to be a uniquely assigned GUID. The main issue is that I don't know how to get & remove this element from the DOM when clicking and firing the removeTrigger handler. Looking at examples, I've seen this within the handler:

model.at(e.target).remove();

but that doesn't work.

Any ideas?!


Solution

  • Instead of passing triggers into the page.render try using a model.ref like so

    For Derby 0.5

    var triggers = model.at('liveaudience.triggers');
    model.subscribe(triggers, function(err){
      model.ref('_page.triggers', triggers);
      page.render();
    });
    

    For Derby 0.3

    model.subscribe('liveaudience.triggers', function(err,scopedModels){
      model.ref('_page.triggers', scopedModels);
      page.render();
    });
    

    Then accessing the triggers in the loop like so

    {{#each _page.triggers}}
    

    This should setup the bindings correctly.

    And then to remove (for Derby 0.5, not absolutely sure for 0.3)

    e.at().remove();