2017년 9월 24일 일요일

5. ENERGY USE CASES
6. ENTERPRISE USE CASES
7. HEALTHCARE USE CASES
8. PUBLIC SERVICES USE CASES
9. RESIDENTIAL USE CASES
9.1 Home Energy Management
9.1.1 Description
이 유스 케이스는 집에서 소비자가 매일 그들 집의 에너지 소비량을 확인하고 홈가전에 대한 원격 액션을 통해 이 소비를 제어할 수 있도록 하여  에너지 소비를 관리하는 것이다. 에너지 데이터를 수집하고 각 데이터를 소비자와 장비들 또는 시장과 시장에 전달함으로써 혁신적인 서비스가 개발될 수 있다.
유스 케이스는 전기 홈 네트워크로부터 에너지 정보를 수집하고 데이터를 수집하고 처리하기 위한 M2M 시스템에 정보를 전달하는 홈 Energy Gateway(EGW)에 집중한다. 그러면 수집된 데이터로부터 서비스가 개발될 수 있다.
EGW는 다음과 같이 다양한 소스(sensors, context)로 부터 수신된 데이터의 초기 처리를 수행한다.

  • 수집된 정보를 합치고 처리한다.
  • 원격의 M2M 시스템으로 어떤 정보를 전달한다. 예를 들어 M2M 시스템을 통해 경보를 전달한다.
  • 어떤 actuators나 appliances의 즉각적인 활성화를 위해 지역적으로 몇몇 정보를 사용한다.
  • 전체적이거나 개별적인 appliance의 소비 정보를 위한 home electrical meter를 포함하여 홈 장치에 연결된다(무선이나 유선으로)
  • 보여줄 수 있는 소비된 에너지 관련 정보를 end-user나 소비자 터미널에 제공한다.(PC, mobile phone, tablet, TV screen, 등)

Ref:[i.6] {HGI-GD017-R3 (Use Cases and Architecture for a Home Energy Management Service}
9.1.2 Srouce
oneM2M-REQ-2012-0058R03 Home Energy Management
Note: from [i.2] ETSI TR 102 935 v2.1.1
9.1.3 Actors
  • User : 홈 가전의 사용자
  • Communication operators : 어떤 프로토콜(예를 들어 지그비, PLC, 블루투스4.0 ...) 을 통해 수집된 정보를 EGW로 전달하고 EGW에서 M2M 시스템으로 전달하는 것을 담당하는
  • Energy gateway SP : 가전으로부터 M2M 시스템으로 까지의 에너지 정보를 수집하고 전송하며 M2M 시스템으로부터 원격 제어/명령을 안전하게 수신하는 역할을 담당하는
  • Application Service Provider : M2M 시스템을 통하여 사용자에게 Home Energy Management(HEM) 어플리케이션을 제공한다.
9.1.4 Pre-conditions
None
9.1.5 Triggers
None
9.1.6 Normal Flow
Figure9-1 Home Energy Management Normal Flow
  1. HEM 어플리케이션(M2M 디바이스)가 home device(s) 정보를 위해 System Operator/SP에 등록한다.
  2. 집에서 M2M 장치(smart meters, eletric lightening, fridge, washing machine 등)일 수 있는 device로부터의 정보는 communication network operator를 통해 Energy Gateway Operator(EGW)에 의해 수집된다. 정보는 방, 온도, 사용, 에너시 소비(room, temperature, occupancy, energy consumption) 등이 될 수 있다.
  3. 수집된 정보는 EGW SP에 저장이 되고 energy gateway에서 처리될 수 있다. 결과적으로 제어 메시지는 energy gateway에 저장된 정책에 따라 energy GW로부터 장치로 돌려보내질 것이다.
  4. 또한 수지보딘 정보는 통신 네트워크를 통해 저장을 위한 M2M 서비스 플랫폼을 포함하고 있는 system operator로 보내질 것이다.
  5. 등록된 어플리케이션(HEM)는 처리할 수 있는 정보를 통보받는다. 그것의 M2M operator는 subscription profile에 따라 HEM 어플리케이션으로 정보를 보내기전에 정보를 처리할 수 있다.
  6. HEM 어플리케이션은 공유되고 수집된 정보에 반응하고 system operator를 통해 제어 메시지를 보낼 수 있다.(예를 들어 홈 장치를 스위치하기 위해 light/appliance 또는 washing machine 등으로)
  7. 제어는 다른 operator를 통과하여 대응하는 M2M 장치로 전파되다.
9.1.7 Alternative Flow
None
9.1.8 Post-conditions
None
9.1.9 High Level Illustration
Figure 9-2 Home Energy Management System High Level Illustration
9.1.10 Potential Requirements
  1. 다음에 요약된 WAMS use case의 그것과 유사하다.
    1. Data collection 과 reporting capability/function
    2. M2M 장치의 원격 제어
    3. 복수의 어플리케이션으로의 정보 수집과 전송
    4. 데이터 저장과 공유
    5. M2M 장치와 collectors로 M2M 시스템의 인증
    6. M2M 어플리케이션으로 M2M 시스템의 인증
    7. 데이터 통합
    8. 네트워크 연결 남용의 방지
    9. Privacy
    10. 어플리케이션 레벨에서의 보안 증명(Security credential) 과 소프트웨어 업그레이드
    11. 더불어 다음 요구사항들을 필요로 한다.
    12. M2M 시스템은 Gateway를 지원할 것이다.
    13. Gateway는 가구 당 또는 복수의 가구당 존재할 수 있다. 예를 들어 Gateway Concentrator
  2. Configuration Management
  3. M2M Devices와 Gateway의 Pre provisioning
    1. M2M 시스템은 M2M Devices/Gateways의 간단하고 확장가능한 pre provisioning을 수행하는 메커니즘을 지원할 것이다.
  4. 복수의 M2M Devices/Gateways의 관리
    1. M2M 어플리케이션 예를 들어 HEM 어플리케이션은 직접 혹은 M2M Service Capabilityies를 통하여서든 하나 이상의 M2M Devices/Gateways과 상호작용 할 수 있을 것이다. 예를 들어 정보 수집, 제어를 위해
    2. HEM 어플리케이션은 소비자들에게 특정 에너지 등급을 제공하기 위해 에너지 파트너들에게 익명의 데이터를 공유할 수 있을 것이다.
  5. 통보를 수신하기 위해 등록을 위한 지원
    1. M2M 시스템은 어플리케이션이 등록하고 변화를 통보받을 수 있도록 하는 메커니즘을 지원할 것이다.
    2. M2M 시스템 operator는 등록하기 위한 HEM 어플리케이션의 등록을 지원할 수 있을 것이다.
  6. 통지의 최적화 지원
    1. M2M 시스템은 혼잡한 통신 네트워크의 상황에서 연결된 장치의 지연된 통지를 위한 메커니즘을 지원할 수 있을 것이다.
  7. 저장과 전달의 지원
    1. M2M 시스템은 다른 연결된 장치들로부터의 정보의 원격접근을 관리하는 메커니즘을 지원할 수 있을 것이다. 지원하는 시점에 M2M 시스템은 주어진 지연과 혹은 범주에 따라 요청을 합치고 요청의 수행을 지연시킬 수 있을 것이다. 예를 들어 M2M 어플리케이션이 장치와 실시간으로 연결될 필요가 없을 때
9.2 Home Energy Management System(HEMS)
10. RETAIL USE CASES
11. TRANSPORTATION USE CASES
12. OTHER USE CASES

2017년 8월 18일 금요일

Testing UI for Multiple Apps

Testing UI for Multiple Apps


Dependencies and Prerequisites

This lesson teaches you to

  1. Set Up UI Automator
  2. Create a UI Automator Test Class
  3. Run UI Automator Tests on a Device or Emulator

You should also read

Try it out

다중앱을 커버하는 사용자 상호작용과 연관된 UI 테스트는 사용자 흐름이 다른 앱들과 시스템 UI와 얽혀있을때 앱이 정확하게 동작하는지 확인해준다. 그러한 흐름의 예는 텍스트를 입력하는 메시징 앱이 안드로이드 contact picker를 띄워서 사용자가 메시지를 보낼 수신자를 선택할 수 있게 하고 나서 사용자가 메시지 보내기 위해 원래 앱으로 제어를 리턴하도록 하는 것이다.
이 문서는  Android Testing Support Library 가 제공하는  UI automator test framework를 사용하여 어떻게 UI 테스트를 작성하는가를 다룬다. UI Automator API는 어떤 액티비티가 포커스를 가지고 있는지 상관없이 장치의 보이는 요소들과 상호작용할 수 있도록 해준다. 당신의 테스트는 컴포넌트에 보여지는 텍스트나 그것의 컨텐츠 디스크립터와 같은 편리한 디스크립터를 사용하여 UI 컴포넌트를 찾을 수 있다. UI Automator 테스트는 안드로이드 4.3(API level 18) 이상에서 동작하는 장치에서 실행할 수 있다. UI Automator 테스팅 프레임워크는 장치 기반의 API이고 Android Testing Support Library test runner와 함께 동작한다.

Set Up UI Automator


UI automator를 사용하여 당신의 UI test를 작성하기 전에 Getting Started with Testing 에 나와 있는데로 당신의 테스트 코드 위치와 프로젝트 디펜던시를 설정해야 한다.
당신의 안드로이드 앱 모듈에 있는 build.gradle 파일에 UI Automator library에 대한 의존성 참조를 셋팅해야 한다:

dependencies {
    ...
    androidTestCompile 'com.android.support.test.uiautomator:uiautomator-v18:2.1.1'
}
 
 
UI Automator 테스팅을 최적화 하기 위해서는 먼저 타겟 앱의 UI 컴포넌트들을 조사하고 그것들에 접근 가능한지 확인해야 한다. 이들 최적화 팁은 다음 두 섹션에서 설명한다.

Inspecting the UI on a device

테스트를 디자인하기 전에, 장치에 보이는 UI 컴포넌트들을 조사한다. 당신의 UI Automator 테스트가 이들 컴포넌트에 접근할 수 있는지 확인하기 위해 이들 컴포넌트들이 보이는 텍스트 라벨과 android:contentDescription 혹은 둘다를 가지고 있는지 체크한다.
장치의 foreground 상에 보이는 UI 컴포넌트들의 특성을 보고 레이아웃 계층을 조사하기 위한 편리한 비주얼 인터페이스를 제공하는 uiautomatorviewer 툴을 제공한다. 이 정보들은 UI Automator를 사용하여 더 매끄러운 테스트를 작성할 수 있도록 해준다. 예를 들어 당신은 특정한 보이는 속성과 매치하는 UI selector를 작성할 수 있다.

uiautomatorviewer 툴을 띄우기 위해:
To launch the uiautomatorviewer tool:
  1. 물리 장치에 타겟 앱을 띄운다.
  2. 개발 머신에 물리장치를 연결한다.
  3. 터미널 윈도우를 열어서 <android-sdk>/tools/ 디렉토리로 이동한다.
  4. 다음 명령을 이용하여 툴을 실행한다.:
    $ uiautomatorviewe
애플리케이션을 위한 UI 속성들을 보기 위해:
  1. uiautomatorviewer 인터페이스 상에서 , Device Screenshot 버튼을 클릭한다..
  2. uiautomatorviewer 툴에 의해 인식된 UI 컴포넌트들을 보여주는 왼족 패널 상의 snapshot 상에 마우스 커서를 가져다댄다. 속성들이 오른쪽 패널 하단에 리스팅되고 오른쪽 패널 상단에는 레이아웃 계층이 표시된다.
  3. 선택적으로 UI Automator에서 접근할 수 없는 UI 컴포넌트들을 보기 위해서는 Toggle NAF Nodes 버튼을 클릭한다. 이들 컴포넌트를 위해서는 제한된 정보만 사용할 수 있다.
안드로이드에 의해 제공되는 UI 컴포넌트들의 일반적인 타입들에 대해 알고 싶다면 User Interface.를 보아라.

Ensuring your Activity is accessible

The UI Automator test framework performs better on apps that have implemented Android accessibility features. When you use UI elements of type View, or a subclass of View from the SDK or Support Library, you don't need to implement accessibility support, as these classes have already done that for you.
Some apps, however, use custom UI elements to provide a richer user experience. Such elements won't provide automatic accessibility support. If your app contains instances of a subclass of View that isn't from the SDK or Support Library, make sure that you add accessibility features to these elements by completing the following steps:
  1. Create a concrete class that extends ExploreByTouchHelper.
  2. Associate an instance of your new class with a specific custom UI element by calling setAccessibilityDelegate().
For additional guidance on adding accessibility features to custom view elements, see Building Accessible Custom Views. To learn more about general best practices for accessibility on Android, see Making Apps More Accessible.

Create a UI Automator Test Class


Your UI Automator test class should be written the same way as a JUnit 4 test class. To learn more about creating JUnit 4 test classes and using JUnit 4 assertions and annotations, see Create an Instrumented Unit Test Class.
Add the @RunWith(AndroidJUnit4.class) annotation at the beginning of your test class definition. You also need to specify the AndroidJUnitRunner class provided in the Android Testing Support Library as your default test runner. This step is described in more detail in Run UI Automator Tests on a Device or Emulator.
Implement the following programming model in your UI Automator test class:
  1. Get a UiDevice object to access the device you want to test, by calling the getInstance() method and passing it an Instrumentation object as the argument.
  2. Get a UiObject object to access a UI component that is displayed on the device (for example, the current view in the foreground), by calling the findObject() method.
  3. Simulate a specific user interaction to perform on that UI component, by calling a UiObject method; for example, call performMultiPointerGesture() to simulate a multi-touch gesture, and setText() to edit a text field. You can call on the APIs in steps 2 and 3 repeatedly as necessary to test more complex user interactions that involve multiple UI components or sequences of user actions.
  4. Check that the UI reflects the expected state or behavior, after these user interactions are performed.
These steps are covered in more detail in the sections below.

Accessing UI Components

The UiDevice object is the primary way you access and manipulate the state of the device. In your tests, you can call UiDevice methods to check for the state of various properties, such as current orientation or display size. Your test can use the UiDevice object to perform device-level actions, such as forcing the device into a specific rotation, pressing D-pad hardware buttons, and pressing the Home and Menu buttons.
It’s good practice to start your test from the Home screen of the device. From the Home screen (or some other starting location you’ve chosen in the device), you can call the methods provided by the UI Automator API to select and interact with specific UI elements.
The following code snippet shows how your test might get an instance of UiDevice and simulate a Home button press:
import org.junit.Before;
import android.support.test.runner.AndroidJUnit4;
import android.support.test.uiautomator.UiDevice;
import android.support.test.uiautomator.By;
import android.support.test.uiautomator.Until;
...
@RunWith(AndroidJUnit4.class)
@SdkSuppress(minSdkVersion = 18)
public class ChangeTextBehaviorTest {

    private static final String BASIC_SAMPLE_PACKAGE
            = "com.example.android.testing.uiautomator.BasicSample";
    private static final int LAUNCH_TIMEOUT = 5000;
    private static final String STRING_TO_BE_TYPED = "UiAutomator";
    private UiDevice mDevice;

    @Before
    public void startMainActivityFromHomeScreen() {
        // Initialize UiDevice instance
        mDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());

        // Start from the home screen
        mDevice.pressHome();

        // Wait for launcher
        final String launcherPackage = mDevice.getLauncherPackageName();
        assertThat(launcherPackage, notNullValue());
        mDevice.wait(Until.hasObject(By.pkg(launcherPackage).depth(0)),
                LAUNCH_TIMEOUT);

        // Launch the app
        Context context = InstrumentationRegistry.getContext();
        final Intent intent = context.getPackageManager()
                .getLaunchIntentForPackage(BASIC_SAMPLE_PACKAGE);
        // Clear out any previous instances
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        context.startActivity(intent);

        // Wait for the app to appear
        mDevice.wait(Until.hasObject(By.pkg(BASIC_SAMPLE_PACKAGE).depth(0)),
                LAUNCH_TIMEOUT);
    }
}
In the example, the @SdkSuppress(minSdkVersion = 18) statement helps to ensure that tests will only run on devices with Android 4.3 (API level 18) or higher, as required by the UI Automator framework.
Use the findObject() method to retrieve a UiObject which represents a view that matches a given selector criteria. You can reuse the UiObject instances that you have created in other parts of your app testing, as needed. Note that the UI Automator test framework searches the current display for a match every time your test uses a UiObject instance to click on a UI element or query a property.
The following snippet shows how your test might construct UiObject instances that represent a Cancel button and a OK button in an app.
UiObject cancelButton = mDevice.findObject(new UiSelector()
        .text("Cancel"))
        .className("android.widget.Button"));
UiObject okButton = mDevice.findObject(new UiSelector()
        .text("OK"))
        .className("android.widget.Button"));
// Simulate a user-click on the OK button, if found.
if(okButton.exists() && okButton.isEnabled()) {
    okButton.click();
}

Specifying a selector

If you want to access a specific UI component in an app, use the UiSelector class. This class represents a query for specific elements in the currently displayed UI.
If more than one matching element is found, the first matching element in the layout hierarchy is returned as the target UiObject. When constructing a UiSelector, you can chain together multiple properties to refine your search. If no matching UI element is found, a UiAutomatorObjectNotFoundException is thrown.
You can use the childSelector() method to nest multiple UiSelector instances. For example, the following code example shows how your test might specify a search to find the first ListView in the currently displayed UI, then search within that ListView to find a UI element with the text property Apps.
UiObject appItem = new UiObject(new UiSelector()
        .className("android.widget.ListView")
        .instance(0)
        .childSelector(new UiSelector()
        .text("Apps")));
As a best practice, when specifying a selector, you should use a Resource ID (if one is assigned to a UI element) instead of a text element or content-descriptor. Not all elements have a text element (for example, icons in a toolbar). Text selectors are brittle and can lead to test failures if there are minor changes to the UI. They may also not scale across different languages; your text selectors may not match translated strings.
It can be useful to specify the object state in your selector criteria. For example, if you want to select a list of all checked elements so that you can uncheck them, call the checked() method with the argument set to true.

Performing Actions

Once your test has obtained a UiObject object, you can call the methods in the UiObject class to perform user interactions on the UI component represented by that object. You can specify such actions as:
The UI Automator testing framework allows you to send an Intent or launch an Activity without using shell commands, by getting a Context object through getContext().
The following snippet shows how your test can use an Intent to launch the app under test. This approach is useful when you are only interested in testing the calculator app, and don't care about the launcher.
public void setUp() {
    ...

    // Launch a simple calculator app
    Context context = getInstrumentation().getContext();
    Intent intent = context.getPackageManager()
            .getLaunchIntentForPackage(CALC_PACKAGE);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
            // Clear out any previous instances
    context.startActivity(intent);
    mDevice.wait(Until.hasObject(By.pkg(CALC_PACKAGE).depth(0)), TIMEOUT);
}

Performing actions on collections

Use the UiCollection class if you want to simulate user interactions on a collection of items (for example, songs in a music album or a list of emails in an Inbox). To create a UiCollection object, specify a UiSelector that searches for a UI container or a wrapper of other child UI elements, such as a layout view that contains child UI elements.
The following code snippet shows how your test might construct a UiCollection to represent a video album that is displayed within a FrameLayout:
UiCollection videos = new UiCollection(new UiSelector()
        .className("android.widget.FrameLayout"));
// Retrieve the number of videos in this collection:
int count = videos.getChildCount(new UiSelector()
        .className("android.widget.LinearLayout"));
// Find a specific video and simulate a user-click on it
UiObject video = videos.getChildByText(new UiSelector()
        .className("android.widget.LinearLayout"), "Cute Baby Laughing");
video.click();
// Simulate selecting a checkbox that is associated with the video
UiObject checkBox = video.getChild(new UiSelector()
        .className("android.widget.Checkbox"));
if(!checkBox.isSelected()) checkbox.click();

Performing actions on scrollable views

Use the UiScrollable class to simulate vertical or horizontal scrolling across a display. This technique is helpful when a UI element is positioned off-screen and you need to scroll to bring it into view.
The following code snippet shows how to simulate scrolling down the Settings menu and clicking on an About tablet option:
UiScrollable settingsItem = new UiScrollable(new UiSelector()
        .className("android.widget.ListView"));
UiObject about = settingsItem.getChildByText(new UiSelector()
        .className("android.widget.LinearLayout"), "About tablet");
about.click();

Verifying Results

The InstrumentationTestCase extends TestCase, so you can use standard JUnit Assert methods to test that UI components in the app return the expected results.
The following snippet shows how your test can locate several buttons in a calculator app, click on them in order, then verify that the correct result is displayed.
private static final String CALC_PACKAGE = "com.myexample.calc";
public void testTwoPlusThreeEqualsFive() {
    // Enter an equation: 2 + 3 = ?
    mDevice.findObject(new UiSelector()
            .packageName(CALC_PACKAGE).resourceId("two")).click();
    mDevice.findObject(new UiSelector()
            .packageName(CALC_PACKAGE).resourceId("plus")).click();
    mDevice.findObject(new UiSelector()
            .packageName(CALC_PACKAGE).resourceId("three")).click();
    mDevice.findObject(new UiSelector()
            .packageName(CALC_PACKAGE).resourceId("equals")).click();

    // Verify the result = 5
    UiObject result = mDevice.findObject(By.res(CALC_PACKAGE, "result"));
    assertEquals("5", result.getText());
}

Run UI Automator Tests on a Device or Emulator


You can run UI Automator tests from Android Studio or from the command-line. Make sure to specify AndroidJUnitRunner as the default instrumentation runner in your project.
To run your UI Automator test, follow the steps for running instrumented tests described in Getting Started with Testing.

2016년 12월 14일 수요일

브라우저 종류를 판단해주는 자바스크립트 함수

- 프로젝트를 진행할때 보면 ie7,8이 크로스브라우징이 안되어서 골치 아플때가 많다..
- Detectizr.js를 사용해서 해결해도 되지만 Detectizr.js는 modernizr.js가 있어야 작동되므로..
- 간단히 ie만 체크해야  할땐 아래 함수를 사용해서 해결하면 도움이 된다.
- 사용법은 출처 및 아래 첨부파일 다운






<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<script>
function checkBrowser(){ // 외부 라이브러리와 충돌을 막고자 모듈화.
    // 브라우저 및 버전을 구하기 위한 변수들.
    'use strict';
    var agent = navigator.userAgent.toLowerCase(),
        name = navigator.appName,
        browser;
    
    // MS 계열 브라우저를 구분하기 위함.
    if(name === 'Microsoft Internet Explorer' || agent.indexOf('trident') > -1 || agent.indexOf('edge/') > -1) {
        browser = 'ie';
        if(name === 'Microsoft Internet Explorer') { // IE old version (IE 10 or Lower)
            agent = /msie ([0-9]{1,}[\.0-9]{0,})/.exec(agent);
            browser += parseInt(agent[1]);
        } else { // IE 11+
            if(agent.indexOf('trident') > -1) { // IE 11 
                browser += 11;
            } else if(agent.indexOf('edge/') > -1) { // Edge
                browser = 'edge';
            }
        }
    } else if(agent.indexOf('safari') > -1) { // Chrome or Safari
        if(agent.indexOf('opr') > -1) { // Opera
            browser = 'opera';
        } else if(agent.indexOf('chrome') > -1) { // Chrome
            browser = 'chrome';
        } else { // Safari
            browser = 'safari';
        }
    } else if(agent.indexOf('firefox') > -1) { // Firefox
        browser = 'firefox';
    }

    // IE: ie7~ie11, Edge: edge, Chrome: chrome, Firefox: firefox, Safari: safari, Opera: opera
    document.getElementsByTagName('html')[0].className = browser;
    document.getElementById("browser_div").innerHTML = "브라우저 타입 : " + browser;
}
</script>
</head>
<body>
<input type="button" onClick="checkBrowser()" value="확인"/>
<br /><div id="browser_div"></div>
</body>
</html>

[출처] http://micropilot.tistory.com/category/Javascript?page=76

Javascript static function example

Javascript static 함수/변수 선언 예


<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Javascript static function demo</title>
<script type="text/javascript">
function Vector2D(x,y) {
     
    this.x = x;
    this.y = y;
     
    // 인스턴스 함수 선언
    this.add =  function(v2d){
        var x = this.x + v2d.x;
        var y = this.y + v2d.y;
        return new Vector2D(x,y);
    }
};
 
// static 변수선언
Vector2D.len = 0;
 
// static 함수 선언
Vector2D.add = function(v1,v2) {
    //alert(this.x); // this.x 를 인식하지 못함
    return new Vector2D(v1.x+v2.x, v1.y+v2.y);
}
 
// 인스턴스 함수 추가선언
Vector2D.prototype.length = function() {
    return Math.sqrt(this.x*this.x + this.y*this.y);
}
 
// 인스턴스 변수 추가선언
Vector2D.prototype.name = 'MyName'; // 이미 생성된 인스턴스에도 포함됨
 
<!-- var v2d = new Vector2D(3,4); -->
var tmp = new Vector2D(1,2);
var resultVec = v2d.add(tmp); // 인스턴스 함수호출
//console.log(resultVec.x);
 
var vec = Vector2D.add(v2d,tmp); // static 함수호출
 
console.log('v2d.length():'+v2d.length()); // 인스턴스 함수호출
console.log('Vector2D.len:'+Vector2D.len); // static 변수사용
 
</script>
</head>
<body>
 
</body>
</html>


2016년 12월 12일 월요일

자바스크립트 eval() 함수를 이용하여 문자열로 표현된 식이나 함수 실행하기

var str = '10 + 20' ;
var ans = eval ( str ); // 문자열을 표현식으로 해석하여 실행하면 위의 산술식이 실행되므로 30을 리턴한다

다음과 같이 함수(익명함수 포함)를 선언하고 즉시 호출하기 위한 코드는 오류를 발생한다. 함수선언은 반드시 마지막 ' } ' 으로 종료되어야 하기 때문이다

function() {
 alert('익명함수 호출실행됨1');
}(); // <-- 함수선언 문법 오류

오류가 발생한 위의 코드를 약간 수정하여 아래의 코드를 실행하면 선언과 동시에 호출할 수 있고 문제 없이 실행된다
괄호 안에 함수를 선언하면 선언문법을 지킬 수 있고, 그 함수를 호출하기 위해 괄호 밖에 함수호출을 위한 괄호를 사용한 것이다


(function() {
 alert('익명함수 호출실행됨1');
})();

다음과 같이 문자열 형식으로 선언된 함수가 있을 때 eval () 함수를 사용해서 실행할 수도 있다
var strFun = "function() { "+
 "alert('익명함수 호출실행됨3'); "+
"}";
eval("("+strFun+")()"); // <-- 함수선언 문법을 지키고 선언과 동시에 실행하기 위해 괄호를 사용한 것이다

[출처] http://micropilot.tistory.com/2752

onSubmit Event example



ID:


<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Javascript onSubmit example</title>

<script>
function checkForm(form1){
 if(form1.id.value == "") {
  alert("ID required");
  form1.id.focus();
  return false;
 }
 else {
  ans = confirm("정말로 전송하시겠어요?");
  return ans;
 }
}
</script>

</head>
<body>
onSubmit.jsp
<form method="post" onSubmit="return checkForm(this);" action="http://localhost/onSubmit.jsp">
ID: <input type="text" name="id"> 
<input type="submit" value="전 송">
</form>

</body>
</html>


onSubmit.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"%>
<html>
<body>
서버에 전송된 ID: 
<%=request.getParameter("id") %>
</body>
</html>

DIV영역 하단부가 상하로 이동하는 예제


And here is my very slick menu!

Toggle


<html>
<head>
 <title>Javascript test</title>
 <script language="javascript">
 
  var active = 1;
  var height = 100;

  function toggle_visible() {
  
   if(active == 0) {
    
    active = 1;
    
    divPlusOne();    
   
   } else if(active == 1){
   
    active = 0; 
     
    divMinusOne();
   
   }
  
  }
  
  function divPlusOne() {
   
   if(height <= 100) {
   
    document.getElementById('testDiv').style.visibility="visible"; 
   
    height = height + 1;
    document.getElementById('testDiv').style.height=height + 'px';  
    
    window.setTimeout('divPlusOne()', 1);
    
   }
  
  }
  
  function divMinusOne() {
   
   if(height >= 20) {
   
    height = height - 1;
    document.getElementById('testDiv').style.height=height + 'px';
    
    window.setTimeout('divMinusOne()', 1);
    
   } else {
   
    document.getElementById('testDiv').style.visibility="hidden";
   
   }
  }
 </script>
</head>
<body>

 <div id="testDiv" style="border: #000000 1px solid; height: 100px;">And here is my very slick menu!</div>
<br />

 <a href="#" onClick="toggle_visible()">Toggle</a><br />
<br />

</body>
</html>

[출처]http://micropilot.tistory.com/category/Javascript?page=75#