I'm using Controller to Fetch URL. I need a way to put Parameter in this POST. These Parameters are selected by users on View & Not Stored yet(I do not know how to store)
Currently I managed to
Display & Route The View with search result coming from API
Display and refresh the page when someone selects a Filter Option
Problem
I got no idea how to record what the users clicked
How do i "re-post" so i can get the new set of results
I read and say people saying POST Fetch should be done in Model ,
Collection is for Store Multiple Models which i don't know in this
scenario?
Collections
Jobs.js
define([
'jquery',
'underscore',
'backbone',
'models/filter'
], function($, _, Backbone,JobListFilterModel){
var Jobs = Backbone.Collection.extend({
url: function () {
return 'http://punchgag.com/api/jobs?page='+this.page+''
},
page: 1,
model: JobListFilterModel
});
return Jobs;
});
Collections Filter.JS
define([
'jquery',
'underscore',
'backbone',
'models/filter'
], function($, _, Backbone,JobListFilterModel){
console.log("Loaded");
var Jobs = Backbone.Collection.extend({
url: function () {
return 'http://punchgag.com/api/jobs?page='+this.page+''
},
page: 1,
model: JobListFilterModel
});
// var donuts = new JobListFilterModel;
// console.log(donuts.get("E"));
return Jobs;
});
Models
Filter.js
define([
'underscore',
'backbone'
], function(_, Backbone){
var JobFilterModel = Backbone.Model.extend({
defaults: {
T: '1', //Task / Event-based
PT: '1', //Part-time
C: '1', //Contract
I: '1' //Internship
}
});
// Return the model for the module
return JobFilterModel;
});
Models
Job.js
define([
'underscore',
'backbone'
], function(_, Backbone){
var JobModel = Backbone.Model.extend({
defaults: {
name: "Harry Potter"
}
});
// Return the model for the module
return JobModel;
});
Router.js
define([
'jquery',
'underscore',
'backbone',
'views/jobs/list',
'views/jobs/filter'
], function($, _, Backbone, JobListView, JobListFilterView){
var AppRouter = Backbone.Router.extend({
routes: {
// Define some URL routes
'seeker/jobs': 'showJobs',
'*actions': 'defaultAction'
},
initialize: function(attr)
{
Backbone.history.start({pushState: true, root: "/"})
},
showJobs: function()
{
var view = new JobListView();
view.$el.appendTo('#bbJobList');
view.render();
console.log(view);
var jobListFilterView = new JobListFilterView();
jobListFilterView.render()
},
defaultAction: function(actions)
{
console.info('defaultAction Route');
console.log('No route:', actions);
}
});
var initialize = function(){
console.log('Router Initialized');// <- To e sure yout initialize method is called
var app_router = new AppRouter();
};
return {
initialize: initialize
};
});
Some Examples would be awesome. Thank you
Fetching means to retrieve (as you probably know), to GET from the server some information.
POST is usually for creating new resources. For instance, saving a new Job would be a POST on the /jobs URL in a REST like API.
In your case, what you probably want is a:
JobCollection which would extend from Backbone Collection and use a JobModel as the model
JobModel which would represents a Job.
You currently already have the JobModel but it has no Collection... And instead you have a Collection of JobFilters, which means that you are handling multiple set of filters. That's probably not what you had in mind?
Assuming you now have a JobCollection that represents the list of all the jobs your views will display, when you do a collection.fetch() on it, it'll GET all the jobs, without any filters.
The question now becomes: how do I pass extra parameters to fetch() in a collection?
There are many ways to do that. As you already have a JobFilterModel, what you can do in your JobFilterModel is implement a method such as:
//jobCollection being the instance of Job collection you want to refresh
refreshJobs: function(jobCollection) {
jobCollection.fetch({reset: true, data: this.toJSON()});
}
A model's toJSON will transform the Model into a nice Javascript object. So for your JobFilterModel, toJSON() will give back something like:
{
T: '1', //Task / Event-based
PT: '1', //Part-time
C: '1', //Contract
I: '1' //Internship
}
Putting it in the data property of the Collection's fetch() option hash will add those to the query to the server. Then, whatever jobs your server answer with, they will be used to reset (that's why reset: true in the options, otherwise it just updates) the collection of jobs. You can then bind in your views on jobCollection "reset" event to know when to re-render.
So, now, your JobFilterModel only 'job' is to store (in memory) the filters the user has chosen, and the JobCollection and JobModel don't know anything about the filters (and they shouldn't). As for storing the JobFilterModel's current status, you can look at Backbone localstorage plugin or save it on your server / get it from your server (using the model's fetch() and save() method).
I hope this helps!
Related
I am having an issue with a method being overwritten on a dependency that is being injected with Require.
Currently I am have a utility that adds and controls some notifacations across our site that you can see below.
define([
'jQuery',
'Underscore',
'Backbone',
'Data',
'Window',
'text!utilities/notify/templates/utility.html'
], function($, _, Backbone, Data, Window, Template) {
var Notify = Backbone.View.extend({
events: {
'click': 'close'
},
initialize: function() {
var self = this;
_.bindAll(this);
// add notify if not in the dom
var element = $('#notify')[0];
if(_.isEmpty(element)) {
var template = _.template(Template, {});
$('body').prepend(template);
}
Data.add([
// notify object
{
id: 'notify',
addToUrl: false,
addToHistory: false
}
]);
}
return new Notify;
});
(This is only a small portion of this file with the relevant data)
The Data dependency is a wrapper to add a few helper methods to deal with Collections. But we do not overload or modify the add method on the Collection in anyway. The problem I am facing is that in every modern evergreen browser (chrome, firefox, etc) Data is injected correctly and Data.add() works as expected. But in IE8 (sadly I have to support this) the Data.add method sudenly executes a function in Googles Adsense async-ads.js file that we use on our page. When this happens its causes a crazy recursion and IE8 gives a stack overflow message.
I am totally perplexed as to how the Data.add() method is being overwritten by a 3rd party JS function! Any ideas would be greatly appriciated!
Included JS Version Info
Backbone 1.0.0
Require 2.1.2
Underscore 1.3.3
EDIT: I've included the code from the Data utility as requested
/**
#appular {utility} data - designed to store variables for apps that multiple modules may need access too. works closely with the router to keep the url updated as well.
#extends backbone.collection
#define Data
*/
define([
'jQuery',
'Underscore',
'Backbone',
'utilities/data/models/data',
'Cookies'
], function($, _, Backbone, DataModel, Cookies){
var Collection = Backbone.Collection.extend({
model: DataModel,
lastChanged: '',
initialize: function() {
_.bindAll(this);
this.on('add', function(model) {
model.on('change', function() {
this.lastChanged = model.get('id');
this.trigger('dataChanged', model.get('id'));
}, this);
}, this);
},
// Sets data based on url data on initial load (ignores any parameters that are not defined in initialize above)
load: function(data) {
var dataInitialized = _.after(data.length, this.finalizeLoad);
_.each(data, function(dataArray) {
var model = this.get(dataArray[0]);
if(!model) {
model = _.find(this.models, function(model) { return model.get('alias').toLowerCase() === dataArray[0].toLowerCase(); });
}
if(model) {
model.set({value: decodeURIComponent(dataArray[1])}, {silent: true});
}
dataInitialized();
}, this);
},
finalizeLoad: function() {
var triggerInitialized = _.after(this.length, this.triggerInitialized);
_.each(this.models, function(model) {
if(model.get('getFromCookie')) {
var cookieName = null;
if(model.get('alias') !== '') {
cookieName = model.get('alias');
} else {
cookieName = model.get('id');
}
model.set({value: Cookies.get(cookieName)});
}
if(model.get('isArray') && _.isString(model.get('value'))) {
var value = model.get('value');
model.set('value', value.split(','));
}
triggerInitialized();
}, this);
},
/**
#doc {event} initialized - fires when all data has been loaded
*/
triggerInitialized: function() {
this.trigger('initialized');
},
/**
#doc {function} getValueOf - shortcut to get model's value
*/
getValueOf: function(name) {
return this.get(name).get('value');
},
/**
#doc {function} setValueOf - shortcut to set model's value
*/
setValueOf: function(name, value) {
return this.get(name).set('value', value);
}
});
return new Collection;
});
URL : http://localhost:3000/dashboard?ID=10400&Name=10400
I'm trying to get the query params ID and Name from the URL but I get undefined. I have also tried backbone-queryparams but still it does not work. Any idea how to get the current URL with params in Backbone Marionette
define([
'jquery',
'backbone',
'marionette',
'modules/dashboard/controllers/dashboardController',
'backbone.queryparmas'
], function ($, Backbone, Marionette, Controller) {
'use strict';
return Marionette.AppRouter.extend({
appRoutes: {
'': 'dashboard'
},
initialize: function(){
console.log( Backbone.history.fragment ); // getting undefined
},
controller: new Controller()
});
});
I had to do this to get the query params. Not sure if there is any better way.
messagedashboard: function () {
var searchParams = window.location.search.slice(1); // returns 'ID=10400&Name=10400'
var getParamsFromSearchParams = $.deparam(searchParams); //changes into object
}
For using $.deparam check jquery.bbq library.
From the example here (https://stackoverflow.com/a/11671457/3780922), it looks like the best option is to set a route with a catchall parameter, which will give you the entire query string.
appRoutes: {
'': 'showDash', //default for blank/empty route
'dashboard': 'showDash',
'dashboard?*queryString' : 'showDash'
},
showDash: function (queryString) {
var params = parseQueryString(queryString);
if(params.foo){
// foo parameters was passed
}
}
You'll have to write your own query string parser, however, but if it is not null, then you have your query parameter passed in the queryString object, which in your example would be "ID=10400&Name=10400"
I have a backboneJS app that has a router that looks
var StoreRouter = Backbone.Router.extend({
routes: {
'stores/add/' : 'add',
'stores/edit/:id': 'edit'
},
add: function(){
var addStoresView = new AddStoresView({
el: ".wrapper"
});
},
edit: function(id){
var editStoresView = new EditStoresView({
el: ".wrapper",
model: new Store({ id: id })
});
}
});
var storeRouter = new StoreRouter();
Backbone.history.start({ pushState: true, hashChange: false });
and a model that looks like:
var Store = Backbone.Model.extend({
urlRoot: "/stores/"
});
and then my view looks like:
var EditStoresView = Backbone.View.extend({
...
render: function() {
this.model.fetch({
success : function(model, response, options) {
this.$el.append ( JST['tmpl/' + "edit"] (model.toJSON()) );
}
});
}
I thought that urlRoot when fetched would call /stores/ID_HERE, but right now it doesn't call that, it just calls /stores/, but I'm not sure why and how to fix this?
In devTools, here is the url it's going for:
GET http://localhost/stores/
This might not be the answer since it depends on your real production code.
Normally the code you entered is supposed to work, and I even saw a comment saying that it works in a jsfiddle. A couple of reasons might affect the outcome:
In your code you changed the Backbone.Model.url() function. By default the url function is
url: function() {
var base =
_.result(this, 'urlRoot') ||
_.result(this.collection, 'url') ||
urlError();
if (this.isNew()) return base;
return base.replace(/([^\/])$/, '$1/') + encodeURIComponent(this.id);
},
This is the function to be used by Backbone to generate the URL for model.fetch();.
You added a custom idAttribute when you declared your Store Model to be like the one in your DB. For example your database has a different id than id itself, but in your code you still use new Model({ id: id }); when you really should use new Model({ customId: id });. What happens behind the scenes is that you see in the url() function it checks if the model isNew(). This function actually checks if the id is set, but if it is custom it checks for that:
isNew: function() {
return !this.has(this.idAttribute);
},
You messed up with Backbone.sync ... lots of things can be done with this I will not even start unless I want to make a paper on it. Maybe you followed a tutorial without knowing that it might affect some other code.
You called model.fetch() "a la" $.ajax style:
model.fetch({
data: objectHere,
url: yourUrlHere,
success: function () {},
error: function () {}
});
This overrides the awesomeness of the Backbone automation. (I think sync takes over from here, don't quote me on that).
Reference: Backbone annotated sourcecode
I am new in SPA's with backbone and I am trying to develop a small app by using backbone and requireJs.
The problem I faced is that I can't extend a view by passing a collection.
Well, this is the view with name MenuView.js
define([
'Backbone'
], function (Backbone) {
var MenuView = Backbone.View.extend({
tagName: 'ul',
render: function () {
_(this.collection).each(function (item) {
this.$el.append(new MenuListView({ model: item }).render().el);
}, this);
return this;
}
});
return new MenuView;
});
and this is the router.js in which the error is appeared
define([
'Underscore',
'Backbone',
'views/menu/menuView',
'views/createNew/createNew',
'collections/menu/menuCollection',
], function (_, Backbone, MenuView, CreateNewView,Menucollection) {
var AppRouter = Backbone.Router.extend({
routes: {
'index': 'index',
'action/:Create': 'Create'
},
index: function () {
CreateNewView.clear();
//----------- HERE IS THE PROBLEM ------------
$('#menu').html(MenuView({ collection: Menucollection.models }).render().el);
},
Create: function () {
CreateNewView.render();
}
});
var initialize = function () {
var appRouter = new AppRouter();
Backbone.history.start();
appRouter.navigate('index', { trigger: true });
};
return {
initialize: initialize
};
});
The error message is "object is not a function". I agreed with this since the MenuView is not a function. I tried to extend the MenuView (MenuView.extend({collection:Menucollection.models})) and the error message was "objet[object,object] has no method extend".
I suppose that the way I am trying to do this, is far away from the correct one.
Could anyone suggest how to do this?
Thanks
#Matti John's solution will work, but it's more of a workaround than a best practice IMHO.
As it is, you initializing your view just by requiring it, which:
Limits you to never accept arguments
Hits performance
Makes it really hard to unit-test if you relay on assigning properties ater constructing an instance.
A module should be returning a 'class' view and not an instance on that view.
In MenuView.js I would replace return new MenuView with return MenuView; and intitalzie it when required in router.js.
Your MenuView.js returns an initialized MenuView, so you could just do:
MenuView.collection = Menucollection
Note I haven't selected the models - I think it's better if you don't use the models as a replacement for your view's collection, since it would be confusing to read the code and not have a Backbone collection as the view's collection. You would also lose the method's contained within the collection (e.g. fetch/update).
If you do this, then you would need to update your loop (each is available as a method for the collection):
this.collection.each(function (item) {
this.$el.append(new MenuListView({ model: item }).render().el);
}, this);
I am trying to implement a simple app which is able to get a collection for a given object_id.
The GET response from the server looks like this:
[
{object_id: 1, text: "msg1"},
{object_id: 1, text: "msg2"},
{object_id: 1, text: "msg3"},
.......
]
My goal is:
render a collection when the user choose an object_id.
The starting point of my code is the following:
this.options = {object_id: 1};
myView = new NeView(_.extend( {el:this.$("#myView")} , this.options));
My question is:
* What is the best way:
1) to set the object_id value in the MyModel in order to
2) trigger the fetch in MyCollection and then
3) trigger the render function in myView?* or to active my goal?
P.S:
My basic code looks like this:
// My View
define([
"js/collections/myCollection",
"js/models/myFeed"
], function (myCollection, MyModel) {
var MyView = Backbone.View.extend({
initialize: function () {
var myModel = new MyModel();
_.bindAll(this, "render");
myModel.set({
object_id: this.options.object_id
}); // here I get an error: Uncaught TypeError: Object function (){a.apply(this,arguments)} has no method 'set'
}
});
return MyView;
});
// MyCollection
define([
"js/models/myModel"
], function (MyModel) {
var MyCollection = Backbone.Collection.extend({
url: function () {
return "http://localhost/movies/" + myModel.get("object_id");
}
});
return new MyCollection
});
//MyModel
define([
], function () {
var MyModel = Backbone.Model.extend({
});
return MyModel
});
There's a few, if not fundamentally things wrong with your basic understanding of Backbone's internals.
First off, define your default model idAttribute, this is what identifies your key you lookup a model with in a collection
//MyModel
define([
], function () {
var MyModel = Backbone.MyModel.extend({
idAttribute: 'object_id'
});
return MyModel
});
in your collection, there is no need to define your URL in the way you defined it, there are two things you need to change, first is to define the default model for your collection and second is to just stick with the base url for your collection
// MyCollection
define([
"js/models/myModel"
], function (MyModel) {
var MyCollection = Backbone.MyCollection.extend({
model: MyModel, // add this
url: function () {
return "http://localhost/movies
}
});
return MyCollection // don't create a new collection, just return the object
});
and then your view could be something along these lines, but is certainly not limited to this way of implementing
// My View
define([
"js/collections/myCollection",
"js/models/myFeed"
], function (MyCollection, MyModel) {
var MyView = Backbone.View.extend({
tagName: 'ul',
initialize: function () {
this.collection = new MyCollection();
this.collection.on('add', this.onAddOne, this);
this.collection.on('reset', this.onAddAll, this);
},
onAddAll: function (collection, options)
{
collection.each(function (model, index) {
that.onAddOne(model, collection);
});
},
onAddOne: function (model, collection, options)
{
// render out an individual model here, either using another Backbone view or plain text
this.$el.append('<li>' + model.get('text') + '</li>');
}
});
return MyView;
});
Take it easy and go step by step
I would strongly recommend taking a closer look at the exhaustive list of tutorials on the Backbone.js github wiki: https://github.com/documentcloud/backbone/wiki/Tutorials%2C-blog-posts-and-example-sites ... try to understand the basics of Backbone before adding the additional complexity of require.js