jQuery MVC architecture - javascript

what is the best way to create MVC architecture in jQuery?
Should I use jQuery.extend()?
jQuery.extend({
View: function(){}
});
...or jQuery Plugin?
(function($) {
$.fn.model = function() { return this; };
})(jQuery);
...or just objects in JavaScript?
var model = {}
var view = {}
var controller = {}
Thank you!

Just use objects in javascript. The view can contain all the knowledge of things like jquery and other UI concerns, while the controller/model can deal with other logic and communication with the server (assuming ajax). I wrote a blog post about this:
MVC Pattern with Javascript

Here is a great approach using jQuery.extend: http://welcome.totheinter.net/tutorials/model-view-controller-in-jquery/

Related

Is Using Javascript inside a jQuery function is a bad practice?

I know basics of both jQuery and JavaScript.I would like to follow a good coding practice. Is using JavaScript inside a jQuery function is a bad practice?
For exapmle:
$(document).ready( function() {
$('#dqualification').change(function() {
document.getElementById("demo").innerHTML = "Resolve following errors";
});
});
Nope, its fine, and it's done all the time.
Consider:
$("#myDiv").on("click", function(){
var a = this;
});
The line var a = this; is pure JavaScript. There is no "jQuery Version" of var a = this;.
jQuery provides convenient ways of doing things in JavaScript that might be difficult to write and code yourself in pure JavaScript. It doesn't replace JavaScript, it just 'adds to it'.
Remember, jQuery is just a JavaScript library. So everything ends up as JavaScript at the end of the day.
It is not directly bad practice, it is more a bit inconsistend. Both is javascript. But why would you do things like in your example? If you have jQuery available, you could use it!
$(function() {
$('#dqualification').change(function() {
$("#demo").html("Resolve following errors");
});
});

Reusing Knockout.js ViewModels

Hi there i'm building multipage application with Knockout.js and i'm facing a problem writing too much duplicated code..
As example in one of my views i have:
var personVm = function {
//properties here
}
personVm.prototype {
//extensions & methods here
}
And at some point i have to use the same ViewModel in some other view.. So i end up duplicating code..
I searched for solutions and require.js is the most common.. But in my case require.js is not suitable and i can't use it. So i will be glad if some one shares some ways to deal with this problem.
Update:
To clear more my question i need some kind of container from which i can grab instances of given ViewModel for my differen views ( which i get from asp.net )
You could use knockouts own ko.utils.extend
var personVm = function {
//properties here
}
personVm.prototype {
//extensions & methods here
}
then, later
var superHeroVm = function() {
var self = this;
self.specialPower = ko.observable();
ko.utils.extend(self, new personVm());
}
Why can't you just keep personVm in a file which you can access from all over and make a new one each time?
thisModel.person = new personVm(data);
otherModel.person = new personVm(data);
Or am I not understanding the problem correctly?

Attribute-based helper with lambda expressions for data-bind for integrating knockout.js with MVC4/5 + Razor

I just tried KnockoutMvc and while I admire the creator's effort, I find it is a little too heavy-handed to be useful in general. However I like to minimize the amount of JavaScript in my Razor views, especially boilerplate JavaScript (like binding my serverside view models to clientside view models).
Is there any library out there that allows you to use syntax like:
<span data-bind="#Html.DataBindFor(m => m.MyProperty)"></span>
Alternatively, if I were to go about trying to write my own, approximately what (very general) components would I need to make the library useful? I am assuming at a minimum I would need:
A custom set of attributes for defining how each model / property / method would be bound
An extension method for use in Razor views to use reflection to find out the attribute values
An extension method for use in Razor to generate the (minimal?) JavaScript to bind the client view model to the Razor Model and functions to call the server while necessary
Finally, assuming this library doesn't exist, is there a good reason it doesn't exist? IE is there no way to really work this problem in generality such that a helper method is, uh, helpful?
The reason I ask is because the library Lib.Web.Mvc.JqGrid has helped me create interactive tables really quickly with absolutely minimal amounts of JavaScript (just enough to format columns and such) and I wonder why the same does not exist for knockout.js.
The get rid of manually translating the server-side models to the client-side view models, you can employ the ko.mapping plugin which is then used like this:
#model ViewModel
<script src="#Url.Content("~/Scripts/knockout.mapping-latest.js")" type="text/javascript"></script>
...
<script type="text/javascript">
function ViewModel(initData) {
var self = this;
ko.mapping.fromJS(initData, {}, self);
// Add custom view model logic
...
// Logic for persisting the current state of the model back to the server
self.Save = function() {
$.ajax('/model-uri', {
type: 'POST',
contentType: "application/json",
data: ko.toJSON(self),
success: function (response) {
alert('Success!');
},
error: function(xhr, status, error) {
alert('Error: ' + xhr.responseText);
}
});
};
var initialData = #(Html.Raw(JsonConvert.SerializeObject(Model)));
var model = new ViewModel(initialData);
ko.applyBindings(model);
</script>
Note that we're serializing the server-provided view model to a JavaScript object and then making its properties observable using the ko.mapping plugin which saves us duplicating the view model definition on the client side. We also employ the ko.toJSON utility function when sending the updated model back to the server.
The mapping procedure can be customized to ignore certain properties:
var mapping = {
'ignore': ["propertyToIgnore", "alsoIgnoreThis"]
}
ko.mapping.fromJS(data, mapping, self);
There are more mapping customizations available, described on the plugin page.

creating basic navigation in backbone

I am a complete noob to backbone and decided to try and create a web page or two based using backbone as a structure. My first task is to create a basic navigation.
My page lives here http://dalydd.com/projects/backbone.html
here is my javascript thus fur to create that one little navigation item
(function($){
var NavigationItem = Backbone.Model.extend({
defaults: {
name: '',
href: '',
last: false,
id: ''
},
initialize: function() {
}
});
var home = new NavigationItem({name: 'home', href: '/home', id:'home'});
var about = new NavigationItem({name:'about', href: '/about'});
var contact = new NavigationItem({name:'contact', href: '/contact', last:true});
var TopNav = Backbone.Collection.extend({
model: NavigationItem,
});
var topNav = new TopNav();
NavView = Backbone.View.extend({
el : $('ul'),
initialize: function(){
_.bindAll(this, 'render');
this.render();
},
render : function() {
var self = this;
$(this.el).append("<li>"+home.get('name')+"</li>")
}
});
var navView = new NavView();
})(jQuery);
My question(s) is how can i loop through each instantiated nav item and append it to the ul element w/o writing each one out
My other question is can you use backbone without data-binding your scripts, data-binding seems like obtrusive javascript in a way. Also does one need to become an expert in underscore.js in order to use backbone properly. Underscore just seems like a bunch of predefined functions - doesn't jQuery offer some of the same functions as utility functions? so why even use underscore is because of the data binding? can you use backbone w/o data-binding everything? I'm having a difficult time learning backbone because I feel like it mimics a classical language instead of using something like Object.create() like Douglas Crockford uses. Are there any resources out there that just build a basic page using backbone? I know it's not intended for small applications but I'm still trying to figure out how it all works.
Again any help/resources is appreciated. I just started working for a large corporation and they are looking to implement an MVC framework for javascript and backbone seems the ideal choice but I am struggling thus far to learn.
Underscore just seems like a bunch of predefined functions - doesn't jQuery offer some of the same functions as utility functions? so why even use underscore is because of the data binding? can you use backbone w/o data-binding everything?
Underscore doesn't deal with the DOM, only with JavaScript. The two are orthogonal.
Underscore is a backbone dependency , you need it to make it work.
jQuery/Zepto is needed if you need to work with the DOM ( and ajax ).
Underscore is used in models and collections at least , whether you use it directly or not.
I'm having a difficult time learning backbone because I feel like it mimics a classical language instead of using something like Object.create() like Douglas Crockford uses.
You need to use the library API when required , or use another lib. Backbone uses prototypal inheritance when Object.create is classical inheritance. JavaScript allows both.
My point is you don't need to use every feature of backbone, but you need to use the basic required features in order to make it work.
Backbone provides Collections for this matter. Any Backbone View can hold a Model or a Collection. In your example you could build a collection like this:
var NavigationCollection = Backbone.Collection.extend({
model : NavigationItem
});
Then, you would create the collection and append all of the items:
var navCollection = new NavigationCollection();
navCollection.add(home);
navCollection.add(about);
navCollection.add(content);
and then you can make a view which just displays it all:
var navView = new NavView({
collection : navCollection
});
being this view something like:
var NavView = Backbone.View.extend({
el : $('ul'),
initialize: function(){
_.bindAll(this, 'render');
this.render();
},
render : function() {
this.collection.each(function (item) {
this.$el.append("<li>" + item.get("name") + "</li>");
}, this);
return this; // remember this for chaining
}
});
You could have a view for displaying each of the individual items (and a subviews attribute, so you can refer to them) or even a template which iterates over this collection.

What is a good and known JavaScript MVC pattern?

What is the best way to manage the JavaScript files and the functions/objects context in an ASP.NET MVC app?
Google says http://javascriptmvc.com/
If you're looking for something like that, you should definitely check out MooTools as they implement classes almost exactly the way you describe. Overall, I've found their approach to be very clean, extensible, and maintainable. For example, here is a class template I use to write all of my classes (note that it uses some MooTools-specific syntax):
var className = new Class ({
Implements: [Events, Options],
options: {
option1: 'option1',
option2: 'option2'
},
initialize: function(options){
this.setOptions(options);
},
function1: function(){
},
function2: function(){
}
});
I put all my js files in the Content/Js folder. Then add URL helpers that allow me to change this in the future. My code isn't online, but I stole the idea from Rob Conery MVC Commerce demo.
Not sure what you mean by "manage...the functions/objects context in ASp.NET MVC app"
I think you're asking how to segment/partition your scripts.
You should separate your JS files into separate chunks of functionality.
yes , but this is not a MooTools unique technique,
this is called Object literal pattern.
i'm looking for a way to manage my ajax app according to the current state od the asp.net mvc
i'm thinking about a main js file that
is responsible for all the calls of js function like:
mainApp = function(){
return {
init: function(){
},
function1: function(){
}
};
};
nut in a way of it fits an mvc app.

Categories

Resources