Skip to content

Instantly share code, notes, and snippets.

@culage
Created December 5, 2013 14:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save culage/7805719 to your computer and use it in GitHub Desktop.
Save culage/7805719 to your computer and use it in GitHub Desktop.

MVCパターンを実装してみる

概要

#85 MVCパターンを実装してみる « C# « a wandering wolf をもとにコード書いてみた。

  • Buttonを押下すると、Textboxに入力した文字列を修飾して表示

という仕様。

修正した点とか、懸念とか

  • viewはモデルの状態を自動的に反映するようにした

  • viewがクリックイベントの監視をしてるのは……いいんだろうか?

素のイベントを整理して、単純にしたイベントを再送出するってのはありなのか? 小物エンジニアの会でオブザーバーパターンのアンチパターンについて発表してきたでそれっぽい例があるけど。

  • EventDispatcher.on がどうにも無理矢理になってしまっている

コード

<html>
<head>
<script src="http://www.google.com/jsapi"></script><script>google.load("jquery", "1");</script>
<script src="http://jashkenas.github.com/coffee-script/extras/coffee-script.js"></script>
<script type="text/coffeescript">
class EventDispatcher
	constructor:-> @list={}
	on:(type, f)-> @list[type] = f
	trigger:(type)-> @list[type](@)

class GroupView extends EventDispatcher
	constructor:()->
		super()
		@textIn  = $("#in" )[0]
		@textOut = $("#out")[0]
		$("#btn").click => @btn_Click()
	getText:->
		@textIn.value
	btn_Click:->
		@trigger "click"
	model_Update:(d)->
		@textOut.value = d.getDecorattedText()

class DecoraterModel extends EventDispatcher
	constructor:->
		super()
		@text=""
	setText:(@text)-> @trigger "update"
	getDecorattedText:-> "<<#{@text}>>"

class Controller
	constructor:(@model, @view)->
		@model.on "update", (=> @view.model_Update(arguments...))
		@view.on "click", (=> @btn_Click())
	btn_Click:->
		@model.setText @view.getText()

main =->
	new Controller(new DecoraterModel(), new GroupView())

main()

</script>
</head>
<body>
<input id="in"  type="text">
<input id="btn" type="button" value="">
<input id="out" type="text">
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment