메모장



backbonejs(5) - collection(1) javascript

collection이란?
Backbone collections는 간단하게 정렬된 models설정이다.
다음과 같은 상황에서 사용되어 진다.
  • Model: Student, Collection: ClassStudents
  • Model: Todo Item, Collection: Todo List
  • Model: Animals, Collection: Zoo

일반적인 collection은 model type중 하나에 사용하지만 model들은 collection의 형태에 제한 받지 않는다.

  • Model: Student, Collection: Gym Class
  • Model: Student, Collection: Art Class
  • Model: Student, Collection: English Class

다음은 일반적인 Model/Collection 예제이다.

var Song = Backbone.Model.extend({

   initialize : function() {

     console.log("Music is the answer");

   }

});


var Album = Backbone.Collection.extend({

   model : Song;

});


- Building a collection


유용한 데이터를 만들어보자.


var Song = Backbone.Model.extend({

   defaults:{

      name:"Not specified",

      artist:"Not specified"

   },

   initialize:function() {

      console.log("Music is the answer");

   }

});


var Album = Backbone.Collection.extend({
   model:Song;
});

var song1 = new Song({name:"How Bizarre", artist:"OMC"});
var song2 = new Song({name:"Sexual Healing", artist:"Marvin Gaye"});
var song3 = new Song({name:"Talk It Over In Bed", artist:"OMC"});
var myAlbum = new Album([song1,song2,song3]);
console.log(myAlbum.models); //[song1,song2,song3]

원문 : http://backbonetutorials.com/what-is-a-collection/


backbonejs(4) - router(1) javascript

router란?
hash tag(#)를 사용할때 backjbone router는 application URL의 routing을 위해 사용되어진다.
전통적인 MVC의 의미에서는 의미론적으로 적절하지 않고 What is a view를 읽는다면 이러한 견해를 향상시킬 것이다.
Backbone "router"는 어떠한 application/feature(URL routing/history 능력이 필요한)에도 매우 유용하다.
정의된 router는 적어도 한가지 router 또는 특정라우터 맵의 함수를 포함하고 있어야한다.
아래의 예는 항상 호출되는 router를 정의했다.

또한 route는 url의 " #"tag후를 해석한다.
application에서 모든 링크는 "#/action"또는 "#action"을 추적한다
.조금 더 좋게 보이자면 hash tag뒤에 slash를 추가한다.(http://example.com/#/user/help)
<script>
var AppRouter = Backbone.Router.extend({
   routes:{
     "#actions":"defaultRoute" //matches http://example.com/#anything-here
  },
  defaultRoute:function(actions){
    //변수는 route정의인 "actions"에서 match된 변수를 넘겨준다.
    alert(actions);
  }
});

//router 초기화
var app_router = new AppRouter;
//bookmarkable URL에 의해 필수적인 단계인 backbone history를 시작한다.
Backbone.history.start();
</script>

<a href="#action">Activate route</a>
<a href="#/route/action">Activate another route</a>
<!-- url의 변경을 알림 -->

* 이전 버전인 backbone 0.5(2011년 7월에 release된)는 Router를 Controller라 불렀었다.
혼란을 피하기 위하여 Backbone Developer는 Router라는 이름으로 바꾸었다.
그러므로 이전 버전의 backbone을 사용하고자 한다면 Backbone.Conroller.extend({*});를 써야한다.

- Dynamic Routing
대부분 framework는 정적인 혼합 그리고 동적인 router parameter를 포함하는 route정의를 허용한다.

예를 들어 익숙한 URL 문자, 변수 id와 함께 우편번호를 회수하고자 한다.
"http://example.com/#/posts/12"와 같은 URL문자열에서 주고 id에 접근하기 원한다면 route는 즉시 실행되어 진다.
아래의 예를 실행해 보자.

<script>
var AppRouter=Backbone.Router.extend({
   routes:{
     "/posts/:id":"getPost",
     "*actions":"defaultRoute" // Backbone은 첫번째 router를 match시켜볼것이다.
   },
   getPost:function(id) {
     //route정의 변수를 여기에 넘겨준다.
     alert("Get post number"+id);
   },
   defaultRoute:function(actions) {
     alert(actions);
   }
});

//router초기화var app_router=new AppRouter;
//bookmarkable URL에 의해 필수적인 단계인 backbone history를 시작한다.
Backbone.history.start();
</script>

<a href="#/posts/120">Post 120</a>
<a href="#/posts/130">Post 130</a>

- Dynamic Routing Cont. ":params" and "*splats"
route가 실행되었을때 Backbone은 두가지형태의 변수를 사용한다.
첫번째는 ":params"이다.":params은 slash사이의 어떠한 URL components도 맞춰본다.

그리고 "*splats"는 URL components의 어떠한 숫자도 맞춰본다.
"*splat"의 특성 때문에 URL(모든 components들을 맞춰 볼)은 최종 변수일 것이다.
route가 정의된 "*splats" or ":params"은 관련된 함수에서 arguments(명령)를 넘겨준다.
"/:route/:action"으로 정의된 route는 call back함수에 ("route" and "action")2가지 변수를 넘겨준다.
":prams"와 "*splats"의 사용방법 예이다.

route:{
   "/posts/:id":"getPost",
   //<a href="h-tp://example.com/#/posts/121">example</a>
   "/download/-path":"downloadFile",
   //<a href="http://example.com/#/download/user/images/hey.gif">download<a/>
   "/:route/:action":"loadView"
   //<a href="http://example.com/#/dashboard/graph">Load Route/ Action View</a>
},
getPost:function(id){
  alert(id);//121
},
downloadFile:function(path){
  alert(path) // user/images/hey.gif
},
loadView:function(route,action){
  alert(route+"_"_+action); //dashboard_graph
}
Route는 강력하다. 만약 SEO로써 hash tag를 실행해야한다면 google seo hashbangs를 검색해보면 된다.

원문 : http://backbonetutorials.com/what-is-a-router/

backbone.js, mustache.js 자료 모음 javascript

- Backbone.js todos vs knockout.js todos
https://gist.github.com/1033617

- 흔하지 않은 backbone.js에 대한 국내 개발자분의 사용 예
http://silexkr.github.com/blog/2012/02/17/backbone-dot-js/

- mustache.js
mustache.js란 간단하게 예제를 보시면 바로 이해 가능하실듯
<script>
 $(document).ready(
 function () {
 var template_vars = {
 name: 'Reuven',
 number_of_children: 3
 }
 var template = "<b>{{name}}</b> has {{number_of_children}} children.";
 var html = Mustache.to_html(template, template_vars);
 $('#target').html(html);
 });
</script>

위와 같이 값에 대한 변수를 설정해 놓고 아래에 {{value}}이런식으로 가져다 사용하고 Mustache를 사용하면 끝.
http://www.linuxjournal.com/content/mustachejs?page=0,0

- handlebar 와 mustache 비교
http://sorescode.com/2010/09/12/benchmarks.html
http://engineering.linkedin.com/frontend/client-side-templating-throwdown-mustache-handlebars-dustjs-and-more

위 내용을 봤을때 handlebar.js가 더 나은듯

- backbone.js 설명 잘 해 놓은 곳
http://codefactory.kr/category/javascript/page/3/

backbonejs(3) - view(1) javascript

view의 내용 전체적으로도 기능이 뛰어나다 느끼지만 Tips and Trick에 있는 <%=%>를 이용한 변수 설정은
business logic과 presentation logic을 분리할 수 있다는 내용은 절정이지 않을까라고 느낀다.

view란?
backbone view는 model들과 같은 application들의 data를 반영시켜준다.
또한 view는 model의 event를 listen하거나 그에 따른 작용을 한다.
이번 장에서는 model을 bind하거나 view를 collection하는 방법을 얘기하지 않지만
view의 기능이나 javascript template library와 함께 view를 사용하는 방법에 대해 집중할려고 한다.
(특히 underscore.js의 .template에 대해서)

dom조작을 위해 jquery1.5를 사용할 것이다. 또는 mootools나 sizzle과 같은 다른 라이브러리도 가능하지만
공식적인 backbone.js 문서는 jquery를 지지하고 있다. backbone.view event는 jquery외에 다른 라이브러리에서는
동작하지 않는다.

search box를 만들어 볼려한다. live 예제는 여기서

SearchView = Backbone.View.extend({
  initialize:function() {
    alert('Alerts suck.");
  }
});

//초기화 함수는 backbone view가 초기화될 때 항상 호출된다.
//class의 생성자를 고려하였다.
var search_view = new SearchView;

- The "el" property

the "el" property는 브라우져의 DOM 객체를 참고하였다. 모든 backbone.js view는 "el"property를 가지고 있고,
"el"을 정의하지 않았다면 backbone.js가 비어있는 div element 소유로 생성할 것이다.

예제에서는 div#search_container를 view의 el 속성에 설정하였다.

<div id="search_container"></div>

<script>
SearchView = Backbone.View.extend({
  SearchView = Backbone.View.extend({
    initialize:function() {
       alert('Alerts suck');
    }
  });

  var search_view = new SearchView({el:$("#search_container")});
});
</script>

명심해야 할 점은 container element를 bind해야한다. 모든 event에서 trigger는 이 element에서 해야한다.

- Loading a template

Backbone.js는 Underscore.js의 자식이다. Underscore.js는 micro-templating해결책을 포함하고 있다.
자세한 내용은 Underscore.js's의 문서에서 참고

view를 초기화할때 "render()"함수를 호출하여 실행해야 한다.
"render()"함수는 jQuery를 사용한 view의 "el"속성을 template에서 로드한다.

<div id="search_container"></div>

<script>
SearchView=Backbone.View.extend({
   initialize:function(){
     this.render();
   },
   render:function(){
     //underscore를 사용하여 template을 compile한다.
     var template=_.template($("#search_template").html(), {});
     //backbone "el"을 통해 compile된 HTML을 로드한다.
     this.el.html(template);
   }
});
var seach_view=new SearchView({el:$("#search_container")});
</script>

<script id="search_template">
<label>Search</label>
<input type="text" id="search_input" />
<input type="button" id="search_button" value="Search" />
</script>

파일에 template이 위치해 있거나, CDN으로 부터 받는다. 이것은 유저들이 당신의 application이 항상cache된다고 확신시켜준다.

- Listening for events

view에 listener를 attach하기 위하여, Backbone.View 속성의 "events"를 사용한다.
event listeners는 "el"속성의 자식노드에도 attach되어 질 수 있다는것을 기억해야 한다.
button에 "click"listener를 attach해보자.

<div id="search_container"></div>

<script>
SearchView=Backbone.View.extend({
   initialize:function() {
     this.rend();
   },
   render:function(){
     var template=_.template($("#search_template").html(), {});
     this.el.html(template);
   },
   events:{
     'click input[type=button]":"doSearch"
   },
   doSearch:function(event){
      //button을 클릭했을때, event.currentTarget과 함께 클릭되어진 element에 접근할 수 있다.
      alert('search for" + $("#search_input").val());
   }
});
</script>

<script id="search_template">
<label>Search</label>
<input type="text" id="search_input" />
<input type="button" id="search_button" value="Search" />
</script>

- Tips and Tricks

Using template variables

<div id="search_container"></div>

<script>
SearchView=Backbone.View.extend({
   initialize:function() {
     this.rend();
   },
   render:function(){
     // Underscore.js Template를 사용하여 variables를 설정한다.
     var variables = {search_label:"My Search"};
     var template=_.template($("#search_template").html(), variables);
     this.el.html(template);
   },
   events:{
     'click input[type=button]":"doSearch"
   },
   doSearch:function(event){
      //button을 클릭했을때, event.currentTarget과 함께 클릭되어진 element에 접근할 수 있다.
      alert('search for" + $("#search_input").val());
   }
});
</script>

<script id="search_template">
//<%=%>로 template variables에 접근 가능하다.
<label><%= search_label%></label>
<input type="text" id="search_input" />
<input type="button" id="search_button" value="Search" />
</script>

원문 : http://backbonetutorials.com/what-is-a-view/

backbonejs(2) - model(2) javascript

- Listening for changes to the model
현재 backbone과 같은 library를 사용하는데 있어 유용한 부분중 하나이다.
model에서의 모든 attribute들은 model의 값이 변하는 것을 감지하는 동작 listener를 가지고 있다.
initialize함수에서 model의 속성의 값이 변하는 매시를 호출하는 함수를 bind 해준다.
아래 조건에서 "person"의 이름을 변경한다면 우리는 그들의 새로운 이름을 alert할 것이다.

 Person = Backbone.Model.extend({
 defaults: {
 name: 'Fetus',
 age: 0,
 children: []
 },
 initialize: function(){
 alert("Welcome to this world");
 this.bind("change:name", function(){
 var name = this.get("name"); // 'Stewie Griffin'
alert("Changed my name to " + name );
 });
 },
 replaceNameAttr: function( name ){
this.set({ name: name });
 }
  });

 var person = new Person({ name: "Thomas", age: 67, children: ['Ryan']});
 person.replaceNameAttr('Stewie Griffin');
 // This triggers a change and will alert()


각각의 attribute으로 변경listener를 bind할 수도 있고 또는 간단하게 'this.bind("change",function(){})';를
사용하여 model에서 모든 속성의 변경 listener를 bind 할 수 있다.

- Fetching, Saving and Destroying

Model들은 기본적으로 server의 request로서 collection의 부분이다.
현재 문서에서는 각각의 model들에 중점을 두고 있다. 후에 collection에서 자세히 다룰 예정이다.

- Tips and Tricks
Get all the current attributes
var
person = new Person({ name: "Thomas", age: 67, children: ['Ryan']});
 var attributes = person.toJSON(); // { name: "Thomas", age: 67, children: ['Ryan']}
 // This simply returns a copy of the current attributes. --
 //위의 명령은 현재 attributes를 간단히 복사하여 돌려준다.--
 delete attributes;
 var attributes = person.attributes;
 //The line above gives a direct reference to the attributes and you should be careful when playing with it.
// Best practise would suggest that you use .set() to edit attributes of a model
//to take advantage of backbone listeners. --
 //위의 명령은 attributes를 직접 참조하고, 선언된 attributes속성을 조심히 다루어야한다.
// 가장 좋은 방법은 backbone listener를 사용하여 model attributes 수정을 .set() method 를 사용하길 제안한다.--

Validate data before you set or save it
Person
= Backbone.Model.extend({
 // If you return a string from the validate function,
 // Backbone will throw an error
 //validation함수로 부터 string값이 return 된다면 backbone은 error를 throw할 것이다.
  validate: function( attributes ){
 if( attributes.age < 0 && attributes.name != "Dr Manhatten" ){
 return "You can't be negative years old";
 }
 },
initialize: function(){
  alert("Welcome to this world");
 this.bind("error", function(model, error){
// We have received an error, log it, alert it or forget it :)
 alert( error );
 });
}
 });
 var person = new Person;
 person.set({ name: "Mary Poppins", age: -1 });
 // Will trigger an alert outputting the error
 delete person;
 var person = new Person;
 person.set({ name: "Dr Manhatten", age: -1 });
 // God have mercy on our souls


- 원문 : http://backbonetutorials.com/what-is-a-model/

1 2 3 4 5 6 7 8 9 10 다음