I am making a small application form using Backbone.js and CodeIgniter but I am having problem with connection to controller.
Can anyone please provide me the full code for that?
My controller name is verfylogin. I have taken username and password from the user, and I have to pass it to the controller.
$(function(){
var Credentials = Backbone.Model.extend({});
var LoginView = Backbone.View.extend({
el: $("#login-form"),
events: {
"click #login": "login"
},
initialize: function(){
var self = this;
this.username = $("#username");
this.password = $("#password");
this.username.change(function(e){
self.model.set({username: $(e.currentTarget).val()});
});
this.password.change(function(e){
self.model.set({password: $(e.currentTarget).val()});
});
},
login: function(){
var username= this.model.get('username');
var password = this.model.get('password');
console.log(username,password);
}
});
window.LoginView = new LoginView({model: new Credentials()});
First, please read the Backbone documentation, look at the examples and test them to really understand how it works. Also, take a look at the Backbone.js tag wiki page.
It's irrelevant what is used for the API (backend), Backbone communicates with the backbend through a REST API which consist of URLs.
To link a Backbone model with a endpoint URL, override the urlRoot property.
var Credentials = Backbone.Model.extend({
// Specify the endpoint URL here
urlRoot: "api/endpoint" // relative
// urlRoot: "http://example.com/api/endpoint" // or absolute
});
Then, use the Backbone view's events hash to manage events within the view. Avoid manually binding jQuery events.
var LoginView = Backbone.View.extend({
events: {
"click #login": "login",
"change #username": "onUsernameChange",
"change #password": "onPasswordChange"
},
initialize: function() {
// create the model here
this.model = new Credentials();
// cache jQuery object within the view
this.$username = this.$("#username");
this.$password = this.$("#password");
},
login: function() {
// just call save to make a post request with the data.
this.model.save();
},
onUsernameChange: function(e) {
this.model.set({ username: this.$username.val() });
},
onPasswordChange: function(e) {
this.model.set({ password: this.$password.val() });
}
});
var loginView = new LoginView({ el: "#login-form" });
That way, the context (this) is available in the events callbacks. Avoid hard-coding the el property and prefer passing it on the initialization of a new view instance.
Handling JSON data posted to a CodeIgniter controller
Since I don't use CodeIgniter, I will refer you to other resources.
Working with restful services in CodeIgniter
Retrieve JSON POST data in CodeIgniter
Post JSON to Codeigniter controller
Get JSON response In Codeigniter
Code Igniter - How to return Json response from controller
Related
I have a login form in my backbone application and I would like to display a view with the status of the user. My login view looks like this:
var LoginView = Backbone.View.extend({
el: $("#login-form"),
events: {
'click button': 'login',
},
initialize: function () { },
login: function (event) {
var self = this;
event.preventDefault();
var url = '/api/auth/login';
$.ajax({
url: url,
type: 'POST',
data: this.$el.serialize(),
success: function () {}
});
}
});
What is the best way of saving the user object, display a login status view and restore it if the page is reloaded?
The whole process looks like this.
User hits the website.
A userSession model is created and assign to the application scope App.currentUser = new App.Models.UserSession()
Do fetch with currentUser App.currentUser.fetch()
According to the return, if there's an existing user session, display the user info. Else, show the login view.
Login view logic, in the success callback. App.currentUser.set(response)
I am using Backbone.js and trying to populate my model using fetch(). The problem I am having is that the returned data is not populating my model. I have found a similar question here. The difference is that inside of my success function I am not seeing any data changes nor is a 'change' event being fired.
The code:
Model
window.Company = Backbone.Model.extend({
urlRoot: "/api/company",
defaults:{
"id":null,
"name":"",
"address":"",
"city":"",
"state":"",
"phone":""
},
events: {
'change': 'doChange'
},
doChange: function(event) {
alert('company changed');
}
})
The Router
var AppRouter = Backbone.Router.extend({
routes:{
"":"home",
"company/:id":"companyDetails"
},
initialize:function () {
var user = new User();
this.headerView = new HeaderView({
model: user
});
$('.header').html(this.headerView.el);
console.log("router initialized.");
},
companyDetails: function (id) {
var company = new Company({
id: id
});
company.fetch({
success: function(){
console.log('company.id is ' + company.id);
console.log('company.name is ' + company.name);
console.log('company.address is ' + company.address);
$("#content").html(new CompanyView({
model: company
}).el);
}
});
}
});
JSON
{"address":"555 Main St","name":"Confused Technologies","id":"8dc206cc-1524-4623-a6cd-97c185a76392","state":"CO","city":"Denver","zip":"80206","phone":"5551212"}
The name and address are always undefined. I have to be overlooking something simple???
Edit
Including the view that erroneously left out passing the model to the template.
View
window.CompanyView = Backbone.View.extend({
initialize:function () {
this.render();
console.log('CompanyView initialized');
},
render:function (eventName) {
$(this.el).html(this.template());
return this;
}
})
The attributes are not stored directly on the model. They are stored in an attributes hash, so you would access them through company.attributes, though company.get(attribute) is the way it's usually done. Along the same lines, you would pass company.toJSON() to your template function, as that returns a cloned hash of the model's attributes.
As for your change event not firing, I assume you mean the change: doChange in the model's events hash. Backbone Models do not actually do anything with an events hash. That's for delegating DOM events on Backbone Views. I bet if you put company.on("change", function (model) { console.log(model.toJSON()); }) before your fetch call and removed the success callback, you'd see your model in the console.
Also, I don't think your $("#content").html... line is going to work like you expect. I'd rewrite your router callback like this:
companyDetails: function (id) {
var company = new CompanyView({
el: "#content",
model: new Company({ id: id })
});
// This line would be better in your view's initialize, replacing company with this.
company.listenTo(company.model, "change", company.render);
company.model.fetch();
}
CompanyView#render would typically pass this.model.toJSON() to a template function that returns html, and pass that to this.$el.html(). So something like this.$el.html(this.template(this.model.toJSON()));
OK. The problem with not updating my model was as far as I can tell an async issue. I updated the success callback to include the data parameter like so:
success: function (data) {
$('#content').html(new CompanyView({
model: data
}).el);
}
Note that I am not passing the company object as the model rather the raw returned data. This solved my model problem.
I mentioned in a comment that this started with my underscore template variables `<%= name %>' etc... being empty. I changed my view to this:
window.CompanyView = Backbone.View.extend({
initialize:function () {
this.render();
console.log('CompanyView initialized');
},
render:function (eventName) {
$(this.el).html(this.template(this.model.toJSON()));
return this;
}
})
Those to things got both my model updated and variables propagating to the template.
I believe my problem relates to scope somehow, as I'm a js newbie. I have a tiny backbone.js example where all I am trying to do is print out a list of items fetched from the server.
$(function(){
// = Models =
// Video
window.Video = Backbone.Model.extend({
defaults: function() {
return {
title: 'No title',
description: 'No description'
};
},
urlRoot: 'api/v1/video/'
});
// VideoList Collection
// To be extended for Asset Manager and Search later...
window.VideoList = Backbone.Collection.extend({
model: Video,
url: 'api/v1/video/'
});
// = Views =
window.VideoListView = Backbone.View.extend({
tagName: 'ul',
render: function(eventName) {
$(this.el).html("");
_.each(this.model.models, function(video) {
$(this.el).append(new VideoListRowView({model:video}).render().el);
}, this);
return this;
}
});
// VideoRow
window.VideoListRowView = Backbone.View.extend({
tagName: "li",
template: _.template("id: <%= id %>; title: <%= title %>"),
className: "asset-video-row",
render: function() {
$(this.el).html(this.template(this.model.toJSON()));
return this;
}
});
// Router
var AppRouter = Backbone.Router.extend({
routes:{
"":"assetManager"
},
assetManager:function() {
this.assetList = new VideoList();
this.assetListView = new VideoListView({model:this.assetList});
this.assetList.fetch();
$('#content').html(this.assetListView.render().el);
}
});
var app = new AppRouter();
Backbone.history.start();
// The following works fine:
window.mylist = new VideoList();
window.mylistview = new VideoListView({model:window.mylist});
});
If I access mylist.fetch(); mylist.toJSON() from the console, mylist populates fine. I can tell that this.assetList.fetch() is accurately fetching the data from the backend, but it doesn't appear to be adding the objects to this.assetList.
The fetch method on Backbone collections is asynchronous:
Fetch the default set of models for this collection from the server, resetting the collection when they arrive. [...] Delegates to Backbone.sync under the covers, for custom persistence strategies.
And Backbone.sync says:
Backbone.sync is the function that Backbone calls every time it attempts to read or save a model to the server. By default, it uses (jQuery/Zepto).ajax to make a RESTful JSON request.
So fetch involves an (asynchronous) AJAX call and that means that you're trying to use the collection before fetch has retrieved the data from the server. Note that fetch supports success and error callbacks so you can do this instead:
var self = this;
this.assetList.fetch({
success: function(collection, response) {
$('#content').html(self.assetListView.render().el);
}
});
Or you could bind a callback to the collection's reset event as fetch will reset the collection. Then render your assetListView when the collection's reset event is triggered.
Also, your assetList is a collection so you should be doing:
this.assetListView = new VideoListView({collection: this.assetList});
and:
window.VideoListView = Backbone.View.extend({
tagName: 'ul',
render: function(eventName) {
$(this.el).html("");
_.each(this.collection.models, function(video) {
// ...
So I've got a pretty simple backbone app with a model, a collection, and a couple of views. I'm fetching the actual data from the server by doing a collection.fetch() at page load.
My problem is that one of my views is a "detail" view, and I want to bind it to a particular model - but I don't have the model yet when the page loads. My code looks a lot like this:
window.App = {
Models: {},
Collections: {},
Views: {},
Routers: {}
}
App.Models.Person = Backbone.Model.extend({
urlRoot: '/api/people'
});
App.Collections.People = Backbone.Collection.extend({
model: App.Models.Person,
url: '/api/people'
});
people = new App.Collections.People()
App.Views.List = Backbone.View.extend({
initialize: function() {
this.collection.bind('reset', this.render());
},
render: function() {
$(this.el).html("We've got " + this.collection.length + " models." )
}
});
listView = new App.Views.List({collection: people})
App.Views.Detail = Backbone.View.extend({
initialize: function() {
this.model.bind('change', this.render());
},
render: function() {
$(this.el).html("Model goes here!")
}
});
App.Routers.Main = Backbone.Router.extend({
routes: {
'/people': 'list',
'/people/:id': 'detail'
},
list: function() {
listView.render();
},
detail: function(id) {
detailView = new App.Views.Detail({model: people.get(id)})
detailView.render()
}
})
main = new App.Routers.Main();
Backbone.history.start();
people.fetch();
But if I start with the detail route active, the people collection is empty, so people.get(id) doesn't return anything, so my new view has this.model undefined, and won't let me bind any events relating to it. The error is:
Uncaught TypeError: Cannot call method 'bind' of undefined
If I start with the list route active, then by the time I click on an item to bring up the detail view people is populated, so everything works.
What's the right way to bind model-related events for a "detail" view when you're fetching the data after page load?
You have a part of the answer here: Backbone.js Collections not applying Models (using Code Igniter)
Indeed, you need to wait that people.fetch finishes its ajax request before to call Backbone.history.start(); and trigger the actual route.
Your code should look like:
// [...]
main = new App.Routers.Main();
peoples.fetch({
success: function (collection, response) {
// The collection is filled, trigger the route
Backbone.history.start();
}
});
You can add a loader on the page and hide it when the collection is loaded.
I wanted to see how i could save a model to server using model.save() method when urlRoot is specified on the extended model, but ajax request never fires when i ask for model.fetch() or do model.save(). note: Is hope this is possible without using Collection i suppose?.
HTML
<div id="placeholder"></div>
<script type="text/template" id="view_template">
Hello <%= name %>, here is your script <%= script %>
</script>
Model
window["model"] = Backbone.Model.extend({
initialize: function () {
console.log("CREATED");
},
defaults:{
name:"Please enter your name",
script:"Hello World"
},
urlRoot: "index.aspx",
validate: function (attrs) {
},
sync: function (method, model, success, error) {
console.log("SYNCING", arguments);
}
});
View
window["view"] = Backbone.View.extend({
template:_.template($("#view_template").html()),
initialize: function () {
console.log("INITIALISED VIEW");
this.model.bind("change","render",this);
},
render: function (model) {
console.log("RENDERING");
$(this.el).append(this.template(model));
return this;
}
});
Application
$("document").ready(function () {
var myModel = new model({
name: "Stack Overflow",
script: "alert('Hi SO')"
});
var myView = new view({
model: myModel,
el: $("#placeholder")
});
console.log("SAVING");
myModel.save();
console.log("FETCHING");
myModel.fetch();
});
as you can see in application i call save & fetch but as per documentation this should fire ajax request with POST -> SAVE & GET -> FETCH. But all it does is log's arguments into console in the sync function.
I think the only reason you are not seeing any Ajax requests is that you have overridden the Model.sync method. Normally you would only do this if you wanted to replace the default Ajax syncing implemented in Backbone.sync. See the following line in Model.fetch in backbone.js:
return (this.sync || Backbone.sync).call(this, 'read', this, options);
I did a quick test with your code and I am seeing the Ajax requests if I rename your Model.sync method.