0

I have simple test app, I want to remove and add tags, I have code like this:

<script id="tags_template" type="text/x-jsrender">
<div class="tags">
    Tags:
    <ul>
    {^{for tags}}
        <li>{{:name}}<a>&times;</a></li>
    {{/for}}
        <li><input /></li>
    </ul>
</div>
</script>

and JS

var $view = $('#view');
var tags_tmpl = $.templates("#tags_template");
var tags = [];
tags_tmpl.link('#view', {tags: tags});
$view.find('input').keydown(function(e) {
    if (e.which == 13) {
        $.observable(tags).insert({name: $(this).val()});
        $(this).val('');
    }
});
$view.find('ul').on('click', 'a', function() {
    // how to remove the tag?
});

Now how can I remove the tag? There is $.observable(array).remove but how can I reference that element in template and how can I get it in javascript?

jcubic
  • 61,973
  • 54
  • 229
  • 402

2 Answers2

1

Yes, your own answer is correct. But you may be interested in using a more data-driven and declarative approach, as follows:

<div id="view"></div>

<script id="items_template" type="text/x-jsrender">
    Items (Hit Enter to add):
    <ul>
        {^{for items}}
            <li>
               {{:name}}
               <a class="remove" data-link="{on ~remove}">&times;</a>
            </li>
        {{/for}}
    </ul>
    <input data-link="{:newName trigger=true:} {on 'keydown' ~insert}"/>
</script>

And

var items_tmpl = $.templates("#items_template");
var items = [];

items_tmpl.link('#view', {items: items}, {
    insert: function(ev) {
        if (ev.which === 13) {
            // 'this' is the data item
            $.observable(items).insert({name: this.newName});
            $.observable(this).setProperty('newName', '');
        }
    },

    remove: function() {
        // 'this' is the data item
        $.observable(items).remove($.inArray(this, items));
    }    
});

Alternatives for remove would be:

    remove: function(ev) {
        var view = $.view(ev.target);
        $.observable(items).remove(view.index);
    }

Or:

    remove: function(ev, eventArgs) {
        var view = $.view(eventArgs.linkCtx.elem);
        $.observable(items).remove(view.index);
    }

http://jsfiddle.net/BorisMoore/f90vn4mg/

BTW new documentation for {on ... event binding coming soon on http://jsviews.com

BorisMoore
  • 8,444
  • 1
  • 16
  • 27
0

Found it in the docs:

$view.find('ul').on('click', 'a', function() {
    var view = $.view(this);
    $.observable(tags).remove(view.index);
});
jcubic
  • 61,973
  • 54
  • 229
  • 402