Search code examples
knockout.jsknockout-mapping-plugintag-it

How to use tagit with knockout


i am using http://aehlke.github.com/tag-it/ in my code how to bind with viewmodel

html

<ul data-bind='jqueryui: "tagit",foreach: Tags' >
            <li class="tagit-choice ui-widget-content ui-state-default ui-corner-all" data-bind='with: $data'>
                <span class="tagit-label" data-bind='text: $data'></span>
                <a class="tagit-close">
                    <span class="text-icon">&times;</span>
                    <span class="ui-icon ui-icon-close"></span>
                </a>
                <input type="hidden" name="item[tags][]" data-bind='value: $data'  style="display: none;">
            </li>
            </ul>

Js code

function AppViewModel() {
var self = this;

function Tag(data) {
            this.Name = data;
        }

self.Tags = ko.observableArray([
            new Tag('red'),
            new Tag('blue'),
            new Tag('green')
        ]);
 }

// Activates knockout.js
ko.applyBindings(new AppViewModel());

Thanks in advance for your assistance!


Solution

  • thanks Cedric no need to write custom binder

    i solve this way link

    $("#mytags").tagit({
     availableTags: JSON.parse(ko.toJSON(_.pluck(AppViewModel.Tags, 'Name'))),
     onTagAdded: function (event, tagval) {
                        //on every add add with id if tag exist in system
                        var newtag = $(tagval).children('span.tagit-label').html();
                        var temp = _.find(AppViewModel.Tags, function (item) { return item.Name() == newtag; });
                        if (temp) {
                                AppViewModel().SelectedTags.push( Tag({ 'Id': temp.Id(), "Name": newtag} ));
                        }
                        else {
                                AppViewModel().SelectedTags.push( Tag({ "Name": newtag} ));
                        }
    
                    },
    onTagRemoved: function (event, tagval) {
                        // do something special
                        var tempTag = $(tagval).children('span.tagit-label').html();
                        AppViewModel().SelectedTags.remove(_.find(SelectedTags(), function (item) { return item.Name == tempTag; }));
                    }});