Search code examples
jquerybackbone.jsrendermarionettereset

Backbone: prevent this.render() from doing reset to the input fields


My form has list of documents, one input field and button.

The Scenario:

  1. I enter the product name in the input field.
  2. I click on the search button
  3. The documents having the that name is rendered but the input field is reset (becomes blank)

How can i prevent the render function from resetting the input field? This is a part of my code:

The View

View.DocumentsView = Marionette.CompositeView.extend({      
    events : {
        "click button.js-Doc-search": "search",
    },
    initialize: function() {
        this.collection = this.model.get("list");
    },
    onRender : function(){      
        // Do something to prevent the reset of the input
    }
});

The Controller

documentsView.on("documents:search", function(name) {
    var that = this;
    var fetchingDocuments = this.request("document:entities", name);
    $.when(fetchingDocuments).done(function(documents) {            
        that.model = documents;
        that.collection = documents.get("list");
        that.render();  
    });
});

Solution

  • You can simply save the value in input field to the current view, model etc when search is clicked, like this.searchTerm = this.$el.find('selector for input').val();

    And when render is called you can just set it back to the input field.

    View.DocumentsView = Marionette.CompositeView.extend({      
      events : {
        "click button.js-Doc-search": "search",
      },
      initialize: function() {
        this.collection = this.model.get("list");
      },
      onRender : function(){      
        // Do the rendering
        if(this.searchTerm)
          this.$el.find('selector for input').val(this.searchTerm);
      }
    });
    

    or if you use a library like rivets to always keep the value and input in sync

    it'll be as simple as

    <input rv-value="view.searchterm"/>
    

    once you configure and bind rivets.