I want to display a simple list of languages.
class Language extends Backbone.Model
defaults:
id: 1
language: 'N/A'
class LanguageList extends Backbone.Collection
model: Language
url: '/languages'
languages = new LanguageList
class LanguageListView extends Backbone.View
el: $ '#here'
initialize: ->
_.bindAll #
#render()
render: ->
languages.fetch()
console.log languages.models
list_view = new LanguageListView
languages.models appears empty, although I checked that the request came in and languages were fetched. Am I missing something?
Thanks.
The fetch call is asynchronous:
fetch collection.fetch([options])
Fetch the default set of models for this collection from the server, resetting the collection when they arrive. The options hash takes success and error callbacks which will be passed (collection, response) as arguments. When the model data returns from the server, the collection will reset.
The result is that your console.log languages.models is getting called before the languages.fetch() call has gotten anything back from the server.
So your render should look more like this:
render: ->
languages.fetch
success: -> console.log languages.models
# # Render should always return #
That should get you something on the console.
It would make more sense to call languages.fetch in initialize and bind #render to the collection's reset event; then you could put things on the page when the collection is ready.
Also, _.bindAll # is rarely needed with CoffeeScript. You should create the relevant methods with => instead.
Related
I have a trouble with asynchronously loaded models in Ember. I thought I have already understood the whole "background Ember magic", but I haven't.
I have two models, let's say foo and boo with these properties:
foo: category: DS.belongsTo("boo", { async: true })
boo color: DS.attr("string")
In my route, I load all foos:
model: function(params) {
return this.store.findAll("task", "");
},
than in my template I render a component: {{my-component model=model}}. In the component's code I need to transform the model into another form, so I have:
final_data: function() {
this.get("model").forEach(function(node) {
console.log(node.get("category"));
});
return {};
}.property("model"),
When I try to access the "category" in the model, my code crashes:
EmberError#http://localhost:4200/assets/vendor.js:25705:15
ember$data$lib$adapters$errors$$AdapterError#http://localhost:4200/assets/vendor.js:69218:7
ember$data$lib$adapters$rest$adapter$$RestAdapter<.handleResponse#http://localhost:4200/assets/vendor.js:70383:16
ember$data$lib$adapters$rest$adapter$$RestAdapter<.ajax/</hash.error#http://localhost:4200/assets/vendor.js:70473:25
jQuery.Callbacks/fire#http://localhost:4200/assets/vendor.js:3350:10
jQuery.Callbacks/self.fireWith#http://localhost:4200/assets/vendor.js:3462:7
done#http://localhost:4200/assets/vendor.js:9518:1
.send/callback#http://localhost:4200/assets/vendor.js:9920:8
It seems to me, like the Ember didn't load the boos. How should I access them right to make Ember load them?
It's trying to load category, but the adapter is encountering some error. Can't tell what from your example.
Check your network tab.
When you access an async association from a template, Ember knows what to do. From code, such as your component's logic, Ember has no idea it needs to retrieve the association until you try to get it. The get will trigger the load, but will return a promise. You can do this:
get_final_data: function() {
Ember.RSVP.Promise.all(this.get("model") . map(node => node.get('category'))
.then(vals => this.set('final_data', vals));
}
As I'm sure you can see, this creates an array of promises for each node's category, calls Promise.all to wait for them all to complete, then stores the result into the final_data property.
Note, this is not a computed property; it's a function/method which must be called at some point, perhaps in afterModel.
let's assume I have this controller
MyApp.LayoutFooterController = Ember.ObjectController.extend
formData:
name: null,
phone: null,
message: null
cleanFormData: ->
#set('formData.name', null)
#set('formData.phone', null)
#set('formData.message', null)
send: () ->
#container.lookup('api:contact').send(
#get('formData.name'),
#get('formData.phone'),
#get('formData.message')
)
#cleanFormData()
For this I've created service class
MyApp.Api ||= {}
MyApp.Api.Contact = Ember.Object.extend
init(#$, #anotherDep) ->
send: (name, phone, message) ->
console.log name, phone, message
and initializer
Ember.Application.initializer
name: 'contact'
initialize: (container, application) ->
container.register 'api:contact', MyApp.Api.Contact
Problem is, that I can not figure out how to set container to be able to resolve my service class dependecies init(#$, #anotherDep) through Ember container.
Can anybody give me explanation, how to use the Ember.js dependecy injection (or service locator, I guess) container to inject other libs or objects?
Maybe, that I'm not doing it well at all.
EDIT
When I looked to Ember's container source code I found a solution:
Ember.Application.initializer
name: 'contact'
initialize: (container, application) ->
container.register 'api:contact', { create: () -> new MyApp.Api.Contact(application.$) }
But is this clean?
Generally you don't want to be wiring up all of the pieces yourself, you want to use needs in your controller to let Ember do it for you. I'm not sure at all how Ember deals with 3 level class names vs two, so I'm just going to demonstrate with two levels. (MyApp.ApiContact instead of MyApp.Api.Contact.) Also, send is a native Ember method that is present on all (or almost all) objects, so you'd want to use something like sendMessage instead so that you don't end up with hard to diagnose conflicts. After you have told Ember that your controller needs apiContact, you can just call this.get('controllers.apiContact') to get a hold of it.
MyApp.LayoutFooterController = Ember.ObjectController.extend({
needs : ['apiContact'],
// All your other stuff here
sendMessage : function(){
this.get('controllers.apiContact').sendMessage(...);
}
});
Hi I am new to backbone and I have a page where I want to display information about a model. When I try to access it on the console it works out fine
Ex:
collection = new Poster.Colections.Posts()
collection.fetch({reset: true})
post = collection.get(1)
Above works fine
Now when I try to do it in a function on the routers page, it returns back undefined
posts_router.js
class Poster.Routers.Posts extends Backbone.Router
routes:
'posts':'index'
'':'index'
'posts/new': 'new'
'posts/:id': 'show'
initialize: ->
#collection = new Poster.Collections.Posts()
#collection.fetch({reset: true})
index: ->
view = new Poster.Views.PostsIndex(collection: #collection)
$('#index_container').html(view.render().el)
show: (id) ->
post = #collection.get(id)
view = new Poster.Views.PostsShow(model: post)
$('#index_container').html(view.render().el)
new: ->
view = new Poster.Views.PostsNew(collection: #collection)
$('#index_container').html(view.render().el)
I am really new to javascript and backbone and I am lost. Can someone please help
As mu already stated fetch is an asynchronous ajax call. So you have to wait for results and then do something. backbone gives you two options
First option: Call fetch with callback object
fetch takes a callback object with success or error
collection = new Poster.Collections.Posts()
collection.fetch
success: ->
console.log 'Collection fetched'
post = collection.get(1)
error: ->
console.error 'Unable to fetch collection'
Second Option: Listen for changes on the collection
When a model is added to a collection (which is done when fetching a collection) a add event is triggered
collection = new Poster.Collections.Posts.extend
initialize: ->
#on 'add', (model) =>
console.log "model #{model} added"
collection.fetch()
List of built-in events
This is a 2 part question. 1) Is there a better way to render a model to a view asynchronously? I'm currently making the ajax request using the fetch method in the model (though I'm calling it explicitly upon initilization), then rendering the templated view using an application event, vent, which gets published from inside the model after the parse method is called. Cool but wonky? 2) Would a blocking fetch method be of use, and is it possible?
The application renders this to the page:
layout
navbar
index
Then it fetches the model and renders this:
layout
navbar
thing
1
something
somethingelse
But, if I don't use the vent trigger, it (expectedly) renders:
layout
navbar
thing
1
null
null
The html templates:
<!-- Region: NavBar -->
<script type="text/template" id="template-navbar">
<div id="navbar">
navbar
</div>
</script>
<!-- View: IndexView -->
<script type="text/template" id="template-index">
<div id="index">
index
</div>
</script>
<!-- View: ThingView -->
<script type="text/template" id="template-thing">
<div id="thing">
thing<br/>
<%= id %><br/>
<%= valOne %><br/>
<%= valTwo %><br/>
</div>
</script>
<!-- Region -->
<div id="default-region">
<!-- Layout -->
<script type="text/template" id="template-default">
layout
<div id="region-navbar">
</div>
<div id="region-content">
</div>
</script>
</div>
app.js:
window.App = { }
# Region
class RegionContainer extends Backbone.Marionette.Region
el: '#default-region'
# Called on the region when the view has been rendered
onShow: (view) ->
console.log 'onShow RegionContainer'
App.RegionContainer = RegionContainer
# Layout
class DefaultLayout extends Backbone.Marionette.Layout
template: '#template-default'
regions:
navbarRegion: '#region-navbar'
contentRegion: '#region-content'
onShow: (view) ->
console.log 'onShow DefaultLayout'
App.DefaultLayout = DefaultLayout
# NavBar (View)
class NavBar extends Backbone.Marionette.ItemView
template: '#template-navbar'
initialize: () ->
console.log 'init App.NavBar'
App.NavBar = NavBar
# Index View
class IndexView extends Backbone.Marionette.ItemView
template: '#template-index'
initialize: () ->
console.log 'init App.IndexView'
App.IndexView = IndexView
# Thing View
class ThingView extends Backbone.Marionette.ItemView
template: '#template-thing'
model: null
initialize: () ->
console.log 'init App.ThingView'
events:
'click .test_button button': 'doSomething'
doSomething: () ->
console.log 'ItemView event -> doSomething()'
App.ThingView = ThingView
# Thing Model
class Thing extends Backbone.Model
defaults:
id: null
valOne: null
valTwo: null
url: () ->
'/thing/' + #attributes.id
initialize: (item) ->
console.log 'init App.Thing'
#fetch()
parse: (resp, xhr) ->
console.log 'parse response: ' + JSON.stringify resp
# resp: {"id":"1","valOne":"something","valTwo":"somethingelse"}
#attributes.id = resp.id
#attributes.valOne = resp.valOne
#attributes.valTwo = resp.valTwo
console.log 'Thing: ' + JSON.stringify #
#
App.MyApp.vent.trigger 'thingisdone'
App.Thing = Thing
# App
$ ->
# Create application, allow for global access
MyApp = new Backbone.Marionette.Application()
App.MyApp = MyApp
# RegionContainer
regionContainer = new App.RegionContainer
# DefaultLayout
defaultLayout = new App.DefaultLayout
regionContainer.show defaultLayout
# Views
navBarView = new App.NavBar
indexView = new App.IndexView
# Show defaults
defaultLayout.navbarRegion.show navBarView
defaultLayout.contentRegion.show indexView
# Allow for global access
App.defaultRegion = regionContainer
App.defaultLayout = defaultLayout
# Set default data for MyQpp (can't be empty?)
data =
that: 'this'
# On application init...
App.MyApp.addInitializer (data) ->
console.log 'init App.MyApp'
# Test
App.modelViewTrigger = ->
console.log 'trigger ajax request via model, render view'
App.MyApp.vent.trigger 'show:thing'
App.timeoutInit = ->
console.log 'init timeout'
setTimeout 'App.modelViewTrigger()', 2000
App.timeoutInit()
# Event pub/sub handling
App.MyApp.vent.on 'show:thing', ->
console.log 'received message -> show:thing'
thing = new App.Thing(id: '1')
App.thingView = new App.ThingView(model: thing)
# I should be able to do this, but it renders null
# App.defaultLayout.contentRegion.show App.thingView
# Testing to see if I could pub from inside model..yes!
App.MyApp.vent.on 'thingisdone', ->
console.log 'received message -> thingisdone'
App.defaultLayout.contentRegion.show App.thingView
MyApp.start data
From a very basic standpoint, throwing aside the specific example that you've provided, here is how I would approach the problem and solution.
A Generic Problem / Solution
Here's a generic version of the problem:
You need to fetch a model by its id.
You need a view to render after the model has been fetched.
This is fairly simple. Attach the model to the view before fetching the data, then use the "sync" event of the model to render the view:
MyView = Backbone.View.extend({
initialize: function(){
this.model.on("sync", this.render, this);
},
render: function(){ ... }
});
myModel = new MyModel({id: someId});
new MyView({
model: myModel
});
myModel.fetch();
Things to note:
I'm setting up the model with its id, and the view with the model before calling fetch on the model. This is needed in order to prevent a race condition between loading the data and rendering the view.
I've specified generic Backbone stuff here. Marionette will generally work the same, but do the rendering for you.
Your Specific Needs
Blocking Fetch
Bad idea, all around. Don't try it.
A blocking fetch will make your application completely unresponsive until the data has returned from the server. This will manifest itself as an application that performs poorly and freezes any time the user tries to do anything.
The key to not doing this is taking advantage of events and ensuring that your events are configured before you actually make the asynchronous call, as shown in my generic example.
And don't call the fetch from within the model's initializer. That's asking for trouble as you won't be able to set up any views or events before the fetch happens. I'm pretty sure this will solve the majority of the problems you're having with the asynchronous call.
Events Between View And Model
First, I would avoid using MyApp.vent to communicate between the model and the view instance. The view already has a reference to the model, so they should communicate directly with each other.
In other words, the model should directly trigger the event and the view should listen to the event on the model. This works in the same way as my simple example, but you can have your model trigger any event you want at any time.
I would also be sure to the use bindTo feature of Marionette's views, to assist in cleaning up the events when the view is closed.
MyView = Backbone.Marionette.ItemView.extend({
initialize: function(){
this.bindTo(this.model, "do:something", this.render, this);
}
});
MyModel = Backbone.Model.extend({
doSomething: function(){
this.trigger('do:something');
}
});
myModel = new MyModel();
new MyView({
model: myModel
});
myModel.doSomething();
Other Items
There are some other items that I think are causing some problems, or leading toward odd situations that will cause problems.
For example, you have too much happening in the DOMReady event: $ ->
It's not that you have too much code being executed from this event, but you have too much code defined within this event. You should not have to do anything more than this:
$ ->
App.MyApp.start(data)
Don't define your Marionette.Application object in this event callback, either. This should be defined on its own, so that you can set up your initializers outside of the DOMReady callback, and then trigger them with the app.start() call.
Take a look at the BBCloneMail sample application for an example on rendering a layout and then populating its regions after loading data and external templates:
source: https://github.com/derickbailey/bbclonemail
live app: http://bbclonemail.heroku.com/
I don't think I'm directly answering your questions the way you might want, but the ideas that I'm presenting should lead you to the answer that you need. I hope it helps at least. :)
See Derick's new suggestion to tackle this common problem at: https://github.com/marionettejs/backbone.marionette/blob/master/upgradeGuide.md#marionetteasync-is-no-longer-supported
In short, move the asynchronous code away from your views, which means you need to provide them with models whose data has already been fetched. From the example in Marionette's upgrade guide:
Marionette.Controller.extend({
showById: function(id){
var model = new MyModel({
id: id
});
var promise = model.fetch();
$.when(promise).then(_.bind(this.showIt, this));
},
showIt: function(model){
var view = new MyView({
model: model
});
MyApp.myRegion.show(view);
}
});
I want to display a simple list of languages.
class Language extends Backbone.Model
defaults:
id: 1
language: 'N/A'
class LanguageList extends Backbone.Collection
model: Language
url: '/languages'
languages = new LanguageList
class LanguageListView extends Backbone.View
el: $ '#here'
initialize: ->
_.bindAll #
#render()
render: ->
languages.fetch()
console.log languages.models
list_view = new LanguageListView
languages.models appears empty, although I checked that the request came in and languages were fetched. Am I missing something?
Thanks.
The fetch call is asynchronous:
fetch collection.fetch([options])
Fetch the default set of models for this collection from the server, resetting the collection when they arrive. The options hash takes success and error callbacks which will be passed (collection, response) as arguments. When the model data returns from the server, the collection will reset.
The result is that your console.log languages.models is getting called before the languages.fetch() call has gotten anything back from the server.
So your render should look more like this:
render: ->
languages.fetch
success: -> console.log languages.models
# # Render should always return #
That should get you something on the console.
It would make more sense to call languages.fetch in initialize and bind #render to the collection's reset event; then you could put things on the page when the collection is ready.
Also, _.bindAll # is rarely needed with CoffeeScript. You should create the relevant methods with => instead.