Search code examples
backbone.js

in backbone.js can a Model be without any url?


I have an app where the menu system is built dynamically using metadata fetched at startup. Based on this data, and menu selections, I need to craft a "filter box" where user can input search criteria. The "main" View consists of a filter box plus a search results panel where result(s) are rendered in accordance with their classes.

Can I model the Filter Box as a Backbone.js Model? It does not have any data fetches from the backend as its composition depends entirely on the menu selections + the metadata? E.g. when user selects "Sales" menu then the filter box might prompt for "Sales Order Number" whereas when user selects "Material" then the filter box might prompt for something else.

I would then use this widget as component of the "main" View, along with a set of results views made up on the fly. As users make their menu selections, this main View will un-render the existing filter box and recompute and re-render a new one. Other components on the screen could query the Filter Box for its settings.

The examples I have seen so far always have a url and a server fetch, save, etc. The only url-free example on the tutorial page says it is a "contrived" example. I was wondering if a backend provider is necessary and programming will be full of gotchas without conforming to this requirement.

Thanks.


Solution

  • You can have models without url property defined. One of the building blocks of Backbone is the Sync object, that will help you when pulling and pushing data, ideally from/to REST endpoints. For this to work you need to tell where the data are served, and to do so you set a value to url on Models or Collections.

    If you don't need server comunication but you just want to use the utilities provided by simple Model or Collection (such as event handling, filtering, etc..) you just don't set url and you are good to go (just keep in mind that methods like fetch or save won't work).