jquerybackbone.jsbackbone-viewsbackbone-eventsbackbone.js-collections

how to make a search form using backbone.js


I am working with Backbone.js for the very first time, and trying to get my head around how it works. I want to make a search form but i am stuck at starting point.

Here is my input search box

<input type="txt" name="" class="mysearch">

and i want to print something (on console) when i type inside this search box. but it doesn't work as expected.

jQuery(document).ready(function(){
var mymodel= Backbone.Model.extend({
    defaults:function(){
        return{
        name:''
        }
    }
});

var mycollection=Backbone.Collection.extend({
    model:mymodel
});
var mynewcollection= new mycollection();
var myview=Backbone.View.extend({
    model:mynewcollection,

    el:'.mysearch',
    initialize:function(){
        console.log("initialize");            
    },
    events:{
        'keypress .mysearch':'search'
    },
    search:function(){
        console.log("at search");
    }
});
new myview;
    console.log("starting");
});    

What am i missing, i don't know. Any help would be appreciated and sorry for dumb question.


Solution

  • You set the context for your view as .mysearch via el:'.mysearch' and at the same time try to listen to the events emitted by .mysearch element under the view scope. You're basically trying to listen to a .mysearch .mysearch element and that obviously won't work in your setup.

    Try

    var myview=Backbone.View.extend({  
        el:'.mysearch',
        initialize:function(){
            console.log("initialize");            
        },
        events:{
            'keypress':'search'
        },
        search:function(){
            console.log("at search");
        }
    });
    

    And a demo https://jsfiddle.net/9kwhw5yj/